/** 
 * Upgrades a group for a specified course. To preserve the group ID we do a raw insert.
 * @param int $courseid The course to create the group for
 * @return int The id of the group created or false if the insert failed.
 */
function groups_db_upgrade_group($courseid, $group)
{
    global $CFG;
    // Check we have a valid course id
    if (!$courseid || !$group || !isset($group->id)) {
        return false;
    }
    $r = addslashes_object($group);
    $sql = "INSERT INTO {$CFG->prefix}groups\n        (id,name,description, enrolmentkey,lang,theme,picture,hidepicture, timecreated,timemodified)\n        VALUES ('{$r->id}','{$r->name}','{$r->description}', '{$r->enrolmentkey}','{$r->lang}',\n        '{$r->theme}','{$r->picture}','{$r->hidepicture}', '{$r->timecreated}','{$r->timemodified}')";
    if ($result = execute_sql($sql)) {
        $record2 = new Object();
        $record2->courseid = $courseid;
        $record2->groupid = $group->id;
        $record2->timeadded = $group->timemodified;
        $groupadded = insert_record('groups_courses_groups', $record2);
        if (!$groupadded) {
            $groupid = false;
        }
    }
    return $group->id;
}
Beispiel #2
0
function quiz_restore_wiki2markdown($restore)
{
    global $CFG;
    $status = true;
    //Convert question->questiontext
    if ($records = get_records_sql("SELECT q.id, q.questiontext, q.questiontextformat\n                                         FROM {$CFG->prefix}question q,\n                                              {$CFG->prefix}backup_ids b\n                                         WHERE b.backup_code = {$restore->backup_unique_code} AND\n                                               b.table_name = 'question' AND\n                                               q.id = b.new_id AND\n                                               q.questiontextformat = " . FORMAT_WIKI)) {
        $i = 0;
        foreach ($records as $record) {
            //Rebuild wiki links
            $record->questiontext = restore_decode_wiki_content($record->questiontext, $restore);
            //Convert to Markdown
            $wtm = new WikiToMarkdown();
            $record->questiontext = $wtm->convert($record->questiontext, $restore->course_id);
            $record->questiontextformat = FORMAT_MARKDOWN;
            $status = update_record('question', addslashes_object($record));
            //Do some output
            $i++;
            if (($i + 1) % 1 == 0) {
                if (!defined('RESTORE_SILENTLY')) {
                    echo ".";
                    if (($i + 1) % 20 == 0) {
                        echo "<br />";
                    }
                }
                backup_flush(300);
            }
        }
    }
    return $status;
}
Beispiel #3
0
 /**
  * syncronizes user fron external db to moodle user table
  *
  * Sync shouid be done by using idnumber attribute, not username.
  * You need to pass firstsync parameter to function to fill in
  * idnumbers if they dont exists in moodle user table.
  *
  * Syncing users removes (disables) users that dont exists anymore in external db.
  * Creates new users and updates coursecreator status of users.
  *
  * @param bool $do_updates  Optional: set to true to force an update of existing accounts
  *
  * This implementation is simpler but less scalable than the one found in the LDAP module.
  *
  */
 function sync_users($do_updates = false)
 {
     global $CFG;
     $pcfg = get_config('auth/db');
     /// list external users
     $userlist = $this->get_userlist();
     $quoteduserlist = implode("', '", addslashes_recursive($userlist));
     $quoteduserlist = "'{$quoteduserlist}'";
     /// delete obsolete internal users
     if (!empty($this->config->removeuser)) {
         // find obsolete users
         if (count($userlist)) {
             $sql = "SELECT u.id, u.username, u.email\n                        FROM {$CFG->prefix}user u\n                        WHERE u.auth='db' AND u.deleted=0 AND u.username NOT IN ({$quoteduserlist})";
         } else {
             $sql = "SELECT u.id, u.username, u.email\n                        FROM {$CFG->prefix}user u\n                        WHERE u.auth='db' AND u.deleted=0";
         }
         $remove_users = get_records_sql($sql);
         if (!empty($remove_users)) {
             print_string('auth_dbuserstoremove', 'auth', count($remove_users));
             echo "\n";
             foreach ($remove_users as $user) {
                 if ($this->config->removeuser == 2) {
                     if (delete_user($user)) {
                         echo "\t";
                         print_string('auth_dbdeleteuser', 'auth', array($user->username, $user->id));
                         echo "\n";
                     } else {
                         echo "\t";
                         print_string('auth_dbdeleteusererror', 'auth', $user->username);
                         echo "\n";
                     }
                 } else {
                     if ($this->config->removeuser == 1) {
                         $updateuser = new object();
                         $updateuser->id = $user->id;
                         $updateuser->auth = 'nologin';
                         if (update_record('user', $updateuser)) {
                             echo "\t";
                             print_string('auth_dbsuspenduser', 'auth', array($user->username, $user->id));
                             echo "\n";
                         } else {
                             echo "\t";
                             print_string('auth_dbsuspendusererror', 'auth', $user->username);
                             echo "\n";
                         }
                     }
                 }
             }
         }
         unset($remove_users);
         // free mem!
     }
     if (!count($userlist)) {
         // exit right here
         // nothing else to do
         return true;
     }
     ///
     /// update existing accounts
     ///
     if ($do_updates) {
         // narrow down what fields we need to update
         $all_keys = array_keys(get_object_vars($this->config));
         $updatekeys = array();
         foreach ($all_keys as $key) {
             if (preg_match('/^field_updatelocal_(.+)$/', $key, $match)) {
                 if ($this->config->{$key} === 'onlogin') {
                     array_push($updatekeys, $match[1]);
                     // the actual key name
                 }
             }
         }
         // print_r($all_keys); print_r($updatekeys);
         unset($all_keys);
         unset($key);
         // only go ahead if we actually
         // have fields to update locally
         if (!empty($updatekeys)) {
             $sql = 'SELECT u.id, u.username
                     FROM ' . $CFG->prefix . 'user u
                     WHERE u.auth=\'db\' AND u.deleted=\'0\' AND u.username IN (' . $quoteduserlist . ')';
             if ($update_users = get_records_sql($sql)) {
                 print "User entries to update: " . count($update_users) . "\n";
                 foreach ($update_users as $user) {
                     echo "\t";
                     print_string('auth_dbupdatinguser', 'auth', array($user->username, $user->id));
                     if (!$this->update_user_record(addslashes($user->username), $updatekeys)) {
                         echo " - " . get_string('skipped');
                     }
                     echo "\n";
                 }
                 unset($update_users);
                 // free memory
             }
         }
     }
     ///
     /// create missing accounts
     ///
     // NOTE: this is very memory intensive
     // and generally inefficient
     $sql = 'SELECT u.id, u.username
             FROM ' . $CFG->prefix . 'user u
             WHERE u.auth=\'db\' AND u.deleted=\'0\'';
     $users = get_records_sql($sql);
     // simplify down to usernames
     $usernames = array();
     foreach ($users as $user) {
         array_push($usernames, $user->username);
     }
     unset($users);
     $add_users = array_diff($userlist, $usernames);
     unset($usernames);
     if (!empty($add_users)) {
         print_string('auth_dbuserstoadd', 'auth', count($add_users));
         echo "\n";
         begin_sql();
         foreach ($add_users as $user) {
             $username = $user;
             $user = $this->get_userinfo_asobj($user);
             // prep a few params
             $user->username = $username;
             $user->modified = time();
             $user->confirmed = 1;
             $user->auth = 'db';
             $user->mnethostid = $CFG->mnet_localhost_id;
             if (empty($user->lang)) {
                 $user->lang = $CFG->lang;
             }
             $user = addslashes_object($user);
             // maybe the user has been deleted before
             if ($old_user = get_record('user', 'username', $user->username, 'deleted', 1, 'mnethostid', $user->mnethostid)) {
                 $user->id = $old_user->id;
                 set_field('user', 'deleted', 0, 'username', $user->username);
                 echo "\t";
                 print_string('auth_dbreviveuser', 'auth', array(stripslashes($user->username), $user->id));
                 echo "\n";
             } elseif ($id = insert_record('user', $user)) {
                 // it is truly a new user
                 echo "\t";
                 print_string('auth_dbinsertuser', 'auth', array(stripslashes($user->username), $id));
                 echo "\n";
                 // if relevant, tag for password generation
                 if ($this->config->passtype === 'internal') {
                     set_user_preference('auth_forcepasswordchange', 1, $id);
                     set_user_preference('create_password', 1, $id);
                 }
             } else {
                 echo "\t";
                 print_string('auth_dbinsertusererror', 'auth', $user->username);
                 echo "\n";
             }
         }
         commit_sql();
         unset($add_users);
         // free mem
     }
     return true;
 }
Beispiel #4
0
/**
 * Function to be run periodically according to the moodle cron
 * Mails new conversations out to participants, checks for any new
 * participants, and cleans up expired/closed conversations
 * @return   bool   true when complete
 */
function dialogue_cron()
{
    global $CFG, $USER;
    $context_cache = array();
    // delete any closed conversations which have expired
    dialogue_delete_expired_conversations();
    // Finds all dialogue entries that have yet to be mailed out, and mails them
    $sql = "SELECT e.* FROM {$CFG->prefix}dialogue_entries e " . "INNER JOIN {$CFG->prefix}dialogue d ON e.dialogueid = d.id " . "WHERE e.timecreated + d.edittime * 60 < " . time() . " AND e.mailed = 0 ";
    if ($entries = get_records_sql($sql)) {
        foreach ($entries as $entry) {
            echo "Processing dialogue entry {$entry->id}\n";
            if (!($userfrom = get_record('user', 'id', $entry->userid))) {
                mtrace("Could not find user {$entry->userid}\n");
                continue;
            }
            // get conversation record
            if (!($conversation = get_record('dialogue_conversations', 'id', $entry->conversationid))) {
                mtrace("Could not find conversation {$entry->conversationid}\n");
            }
            if ($userfrom->id == $conversation->userid) {
                if (!($userto = get_record('user', 'id', $conversation->recipientid))) {
                    mtrace("Could not find use {$conversation->recipientid}\n");
                }
            } else {
                if (!($userto = get_record('user', 'id', $conversation->userid))) {
                    mtrace("Could not find use {$conversation->userid}\n");
                }
            }
            $USER->lang = $userto->lang;
            if (!($dialogue = get_record('dialogue', 'id', $conversation->dialogueid))) {
                echo "Could not find dialogue id {$conversation->dialogueid}\n";
                continue;
            }
            if (!($course = get_record('course', 'id', $dialogue->course))) {
                echo "Could not find course {$dialogue->course}\n";
                continue;
            }
            if (!($cm = get_coursemodule_from_instance('dialogue', $dialogue->id, $course->id))) {
                echo "Course Module ID was incorrect\n";
            }
            if (empty($context_cache[$course->id])) {
                $context_cache[$course->id] = get_context_instance(CONTEXT_COURSE, $course->id);
            }
            if (!has_capability('mod/dialogue:participate', $context_cache[$course->id], $userfrom->id) && !has_capability('mod/dialogue:manage', $context_cache[$course->id], $userfrom->id)) {
                set_field('dialogue_entries', 'mailed', '1', 'id', $entry->id);
                continue;
                // Not an active participant
            }
            if (!has_capability('mod/dialogue:participate', $context_cache[$course->id], $userto->id) && !has_capability('mod/dialogue:manage', $context_cache[$course->id], $userto->id)) {
                set_field('dialogue_entries', 'mailed', '1', 'id', $entry->id);
                continue;
                // Not an active participant
            }
            $strdialogues = get_string('modulenameplural', 'dialogue');
            $strdialogue = get_string('modulename', 'dialogue');
            $dialogueinfo = new object();
            $dialogueinfo->userfrom = fullname($userfrom);
            $dialogueinfo->dialogue = format_string($dialogue->name);
            $dialogueinfo->url = "{$CFG->wwwroot}/mod/dialogue/view.php?id={$cm->id}";
            $postsubject = "{$course->shortname}: {$strdialogues}: {$dialogueinfo->dialogue}: " . get_string('newentry', 'dialogue');
            $posttext = "{$course->shortname} -> {$strdialogues} -> {$dialogueinfo->dialogue}\n";
            $posttext .= "---------------------------------------------------------------------\n";
            $posttext .= get_string('dialoguemail', 'dialogue', $dialogueinfo) . " \n";
            $posttext .= "---------------------------------------------------------------------\n";
            if ($userto->mailformat == 1) {
                // HTML
                $posthtml = "<p><font face=\"sans-serif\">" . "<a href=\"{$CFG->wwwroot}/course/view.php?id={$course->id}\">{$course->shortname}</a> ->" . "<a href=\"{$CFG->wwwroot}/mod/dialogue/index.php?id={$course->id}\">dialogues</a> ->" . "<a href=\"{$CFG->wwwroot}/mod/dialogue/view.php?id={$cm->id}\">" . $dialogueinfo->dialogue . "</a></font></p>";
                $posthtml .= "<hr /><font face=\"sans-serif\">";
                $posthtml .= '<p>' . get_string('dialoguemailhtml', 'dialogue', $dialogueinfo) . '</p>';
                $posthtml .= "</font><hr />";
            } else {
                $posthtml = '';
            }
            if (!email_to_user($userto, $userfrom, $postsubject, $posttext, $posthtml)) {
                mtrace("Error: dialogue cron: Could not send out mail for id {$entry->id} to user {$userto->id} ({$userto->email})\n");
            }
            if (!set_field('dialogue_entries', 'mailed', '1', 'id', $entry->id)) {
                mtrace("Could not update the mailed field for id {$entry->id}\n");
            }
        }
    }
    /// Find conversations sent to all participants and check for new participants
    $rs = get_recordset_select('dialogue_conversations', 'grouping != 0 AND grouping IS NOT NULL', 'dialogueid, grouping');
    $dialogueid = 0;
    $grouping = 0;
    $groupid = null;
    $inconversation = array();
    $newusers = array();
    while ($conversation = rs_fetch_next_record($rs)) {
        if ($dialogueid != $conversation->dialogueid || $groupid != $conversation->groupid || $grouping != $conversation->grouping) {
            if ($dialogueid == 0 || $groupid === null) {
                $dialogueid = $conversation->dialogueid;
                $groupid = $conversation->groupid;
            }
            $cm = get_coursemodule_from_instance('dialogue', $dialogueid);
            $context = get_context_instance(CONTEXT_MODULE, $cm->id);
            $users = (array) get_users_by_capability($context, 'mod/dialogue:participate', 'u.id, u.firstname, u.lastname', null, null, null, empty($groupid) ? null : $groupid, null, null, null, false);
            $managers = (array) get_users_by_capability($context, 'mod/dialogue:manage', 'u.id, u.firstname, u.lastname', null, null, null, null, null, null, null, false);
            $dialogueid = $conversation->dialogueid;
            $groupid = $conversation->groupid;
        }
        if ($grouping != $conversation->grouping) {
            if ($grouping) {
                if ($userdiff = array_diff_key($users, $inconversation, $managers)) {
                    foreach ($userdiff as $userid => $value) {
                        $newusers[$userid . ',' . $grouping] = array('userid' => $userid, 'courseid' => $cm->course, 'grouping' => $grouping);
                    }
                }
            }
            $inconversation = array();
            $grouping = $conversation->grouping;
        }
        $inconversation[$conversation->recipientid] = true;
    }
    if (!empty($dialogueid)) {
        // Finish of any remaing users
        $cm = get_coursemodule_from_instance('dialogue', $dialogueid);
        $context = get_context_instance(CONTEXT_MODULE, $cm->id);
        $users = (array) get_users_by_capability($context, 'mod/dialogue:participate', 'u.id, u.firstname, u.lastname', null, null, null, empty($groupid) ? null : $groupid, null, null, null, false);
        $managers = (array) get_users_by_capability($context, 'mod/dialogue:manage', 'u.id, u.firstname, u.lastname', null, null, null, null, null, null, null, false);
        if ($userdiff = array_diff_key($users, $inconversation, $managers)) {
            foreach ($userdiff as $userid => $value) {
                $newusers[$userid . ',' . $grouping] = array('userid' => $userid, 'courseid' => $cm->course, 'grouping' => $grouping);
            }
        }
    }
    rs_close($rs);
    if (!empty($newusers)) {
        foreach ($newusers as $key => $newuser) {
            begin_sql();
            course_setup($newuser['courseid']);
            if ($conversations = get_records('dialogue_conversations', 'grouping', $newuser['grouping'], 'id', '*', 0, 1)) {
                $conversation = array_pop($conversations);
                // we only need one to get the common field values
                if ($entry = get_records('dialogue_entries', 'conversationid', $conversation->id, 'id', '*', 0, 1)) {
                    unset($conversation->id);
                    $conversation->recipientid = $newuser['userid'];
                    $conversation->lastrecipientid = $newuser['userid'];
                    $conversation->timemodified = time();
                    $conversation->seenon = false;
                    $conversation->closed = 0;
                    $conversation = addslashes_object($conversation);
                    if (!($conversationid = insert_record('dialogue_conversations', $conversation))) {
                        rollback_sql();
                        continue;
                    }
                    $entry = array_pop($entry);
                    $srcentry = clone $entry;
                    unset($entry->id);
                    $entry->conversationid = $conversationid;
                    $entry->timecreated = $conversation->timemodified;
                    $entry->recipientid = $conversation->recipientid;
                    $entry->mailed = false;
                    $entry = addslashes_object($entry);
                    if (!($entry->id = insert_record('dialogue_entries', $entry))) {
                        rollback_sql();
                        continue;
                    }
                    $read = new stdClass();
                    $lastread = time();
                    $read->conversationid = $conversationid;
                    $read->entryid = $entry->id;
                    $read->userid = $conversation->userid;
                    $read->firstread = $lastread;
                    $read->lastread = $lastread;
                    insert_record('dialogue_read', $read);
                    if ($entry->attachment) {
                        $srcdir = dialogue_file_area($srcentry);
                        $dstdir = dialogue_file_area($entry);
                        copy($srcdir . '/' . $entry->attachment, $dstdir . '/' . $entry->attachment);
                    }
                } else {
                    mtrace('Failed to find entry for conversation: ' . $conversation->id);
                }
            } else {
                mtrace('Failed to find conversation: ' . $conversation->id);
            }
            commit_sql();
        }
    }
    return true;
}
Beispiel #5
0
                $a->user = fullname($user);
                email_to_user($teacher, $user, get_string("enrolmentnew", '', $course->shortname), get_string('enrolmentnewuser', '', $a));
            }
            if (!empty($CFG->enrol_mailadmins)) {
                $a->course = $course->fullname;
                $a->user = fullname($user);
                $admins = get_admins();
                foreach ($admins as $admin) {
                    email_to_user($admin, $user, get_string("enrolmentnew", '', $course->shortname), get_string('enrolmentnewuser', '', $a));
                }
            }
        }
    } else {
        if (strcmp($result, "INVALID") == 0) {
            // ERROR
            insert_record("enrol_paypal", addslashes_object($data), false);
            email_paypal_error_to_admin("Received an invalid payment notification!! (Fake payment?)", $data);
        }
    }
}
fclose($fp);
exit;
/// FUNCTIONS //////////////////////////////////////////////////////////////////
function email_paypal_error_to_admin($subject, $data)
{
    $admin = get_admin();
    $site = get_site();
    $message = "{$site->fullname}:  Transaction failed.\n\n{$subject}\n\n";
    foreach ($data as $key => $value) {
        $message .= "{$key} => {$value}\n";
    }
function kaltura_restore_wiki2markdown($restore)
{
    global $CFG;
    $status = true;
    return $status;
    //Convert resource->alltext
    if ($records = get_records_sql("SELECT r.id, r.alltext, r.options\n                                         FROM {$CFG->prefix}resource r,\n                                              {$CFG->prefix}backup_ids b\n                                         WHERE r.course = {$restore->course_id} AND\n                                               options = " . FORMAT_WIKI . " AND\n                                               b.backup_code = {$restore->backup_unique_code} AND\n                                               b.table_name = 'resource' AND\n                                               b.new_id = r.id")) {
        foreach ($records as $record) {
            //Rebuild wiki links
            $record->alltext = restore_decode_wiki_content($record->alltext, $restore);
            //Convert to Markdown
            $wtm = new WikiToMarkdown();
            $record->alltext = $wtm->convert($record->alltext, $restore->course_id);
            $record->options = FORMAT_MARKDOWN;
            $status = update_record('resource', addslashes_object($record));
            //Do some output
            $i++;
            if (($i + 1) % 1 == 0) {
                if (!defined('RESTORE_SILENTLY')) {
                    echo ".";
                    if (($i + 1) % 20 == 0) {
                        echo "<br />";
                    }
                }
                backup_flush(300);
            }
        }
    }
    return $status;
}
Beispiel #7
0
 function import()
 {
     global $CFG;
     list($settings, $newfields, $currentfields) = $this->get_settings();
     $preservedfields = array();
     $overwritesettings = optional_param('overwritesettings', 0, PARAM_BOOL);
     /* Maps fields and makes new ones */
     if (!empty($newfields)) {
         /* We require an injective mapping, and need to know what to protect */
         foreach ($newfields as $nid => $newfield) {
             $cid = optional_param("field_{$nid}", -1, PARAM_INT);
             if ($cid == -1) {
                 continue;
             }
             if (array_key_exists($cid, $preservedfields)) {
                 error("Not an injective map");
             } else {
                 $preservedfields[$cid] = true;
             }
         }
         foreach ($newfields as $nid => $newfield) {
             $cid = optional_param("field_{$nid}", -1, PARAM_INT);
             /* A mapping. Just need to change field params. Data kept. */
             if ($cid != -1 and isset($currentfields[$cid])) {
                 $fieldobject = data_get_field_from_id($currentfields[$cid]->id, $this->data);
                 foreach ($newfield as $param => $value) {
                     if ($param != "id") {
                         $fieldobject->field->{$param} = $value;
                     }
                 }
                 unset($fieldobject->field->similarfield);
                 $fieldobject->update_field();
                 unset($fieldobject);
             } else {
                 include_once "field/{$newfield->type}/field.class.php";
                 if (!isset($newfield->description)) {
                     $newfield->description = '';
                 }
                 $classname = 'data_field_' . $newfield->type;
                 $fieldclass = new $classname($newfield, $this->data);
                 $fieldclass->insert_field();
                 unset($fieldclass);
             }
         }
     }
     /* Get rid of all old unused data */
     if (!empty($preservedfields)) {
         foreach ($currentfields as $cid => $currentfield) {
             if (!array_key_exists($cid, $preservedfields)) {
                 /* Data not used anymore so wipe! */
                 print "Deleting field {$currentfield->name}<br />";
                 $id = $currentfield->id;
                 //Why delete existing data records and related comments/ratings??
                 /*
                                     if ($content = get_records('data_content', 'fieldid', $id)) {
                                         foreach ($content as $item) {
                                             delete_records('data_ratings', 'recordid', $item->recordid);
                                             delete_records('data_comments', 'recordid', $item->recordid);
                                             delete_records('data_records', 'id', $item->recordid);
                                         }
                                     }*/
                 delete_records('data_content', 'fieldid', $id);
                 delete_records('data_fields', 'id', $id);
             }
         }
     }
     // handle special settings here
     if (!empty($settings->defaultsort)) {
         if (is_numeric($settings->defaultsort)) {
             // old broken value
             $settings->defaultsort = 0;
         } else {
             $settings->defaultsort = (int) get_field('data_fields', 'id', 'dataid', $this->data->id, 'name', addslashes($settings->defaultsort));
         }
     } else {
         $settings->defaultsort = 0;
     }
     // do we want to overwrite all current database settings?
     if ($overwritesettings) {
         // all supported settings
         $overwrite = array_keys((array) $settings);
     } else {
         // only templates and sorting
         $overwrite = array('singletemplate', 'listtemplate', 'listtemplateheader', 'listtemplatefooter', 'addtemplate', 'rsstemplate', 'rsstitletemplate', 'csstemplate', 'jstemplate', 'asearchtemplate', 'defaultsortdir', 'defaultsort');
     }
     // now overwrite current data settings
     foreach ($this->data as $prop => $unused) {
         if (in_array($prop, $overwrite)) {
             $this->data->{$prop} = $settings->{$prop};
         }
     }
     data_update_instance(addslashes_object($this->data));
     if (strstr($this->folder, '/temp/')) {
         // Removes the temporary files
         clean_preset($this->folder);
     }
     return true;
 }
function journal_restore_wiki2markdown($restore)
{
    global $CFG;
    $status = true;
    //Convert journal_entries->text
    if ($records = get_records_sql("SELECT e.id, e.text, e.format\n                                         FROM {$CFG->prefix}journal_entries e,\n                                              {$CFG->prefix}journal j,\n                                              {$CFG->prefix}backup_ids b\n                                         WHERE j.id = e.journal AND\n                                               j.course = {$restore->course_id} AND\n                                               e.format = " . FORMAT_WIKI . " AND\n                                               b.backup_code = {$restore->backup_unique_code} AND\n                                               b.table_name = 'journal_entries' AND\n                                               b.new_id = e.id")) {
        foreach ($records as $record) {
            //Rebuild wiki links
            $record->text = restore_decode_wiki_content($record->text, $restore);
            //Convert to Markdown
            $wtm = new WikiToMarkdown();
            $record->text = $wtm->convert($record->text, $restore->course_id);
            $record->format = FORMAT_MARKDOWN;
            $status = update_record('journal_entries', addslashes_object($record));
            //Do some output
            $i++;
            if (($i + 1) % 1 == 0) {
                if (!defined('RESTORE_SILENTLY')) {
                    echo ".";
                    if (($i + 1) % 20 == 0) {
                        echo "<br />";
                    }
                }
                backup_flush(300);
            }
        }
    }
    //Convert journal->intro
    if ($records = get_records_sql("SELECT j.id, j.intro, j.introformat\n                                         FROM {$CFG->prefix}journal j,\n                                              {$CFG->prefix}backup_ids b\n                                         WHERE j.course = {$restore->course_id} AND\n                                               j.introformat = " . FORMAT_WIKI . " AND\n                                               b.backup_code = {$restore->backup_unique_code} AND\n                                               b.table_name = 'journal' AND\n                                               b.new_id = j.id")) {
        foreach ($records as $record) {
            //Rebuild wiki links
            $record->intro = restore_decode_wiki_content($record->intro, $restore);
            //Convert to Markdown
            $wtm = new WikiToMarkdown();
            $record->intro = $wtm->convert($record->intro, $restore->course_id);
            $record->introformat = FORMAT_MARKDOWN;
            $status = update_record('journal', addslashes_object($record));
            //Do some output
            $i++;
            if (($i + 1) % 1 == 0) {
                if (!defined('RESTORE_SILENTLY')) {
                    echo ".";
                    if (($i + 1) % 20 == 0) {
                        echo "<br />";
                    }
                }
                backup_flush(300);
            }
        }
    }
    return $status;
}
function AutenticarUsuarioContenido($usrcontent)
{
    global $CFG;
    //save log registering the request data
    add_to_log(1, 10, serialize($usrcontent));
    $result = new AutenticarUsuarioContenidoResponse();
    $auth = UserAuthentication($GLOBALS["HTTP_RAW_POST_DATA"]);
    if ($auth->Codigo == '1') {
        //if book exists
        if ($book = get_record("books_credentials", 'isbn', $usrcontent->ISBN)) {
            //if credential of the book exists
            if ($book_credential = get_record("books_credentials", 'isbn', $usrcontent->ISBN, 'credentials', $usrcontent->Credencial)) {
                $result->AutenticarUsuarioContenidoResult->Codigo = $book_credential->code;
                $result->AutenticarUsuarioContenidoResult->Descripcion = $book_credential->description;
                $result->AutenticarUsuarioContenidoResult->URL = $book_credential->url;
                //XTEC *********** AFEGIT -> Check if isset parameter Rol and if one off the tow allowed values
                //2011.05.16  @mmartinez
                if (isset($usrcontent->Rol)) {
                    $alloweb_values = array("ESTUDIANTE", "PROFESOR");
                    if (!in_array($usrcontent->Rol, $alloweb_values)) {
                        $result->AutenticarUsuarioContenidoResult->Codigo = "-7";
                        $result->AutenticarUsuarioContenidoResult->Descripcion = "Rol incorrecte. El valor del rol &eacute;s incorrecte";
                        $result->AutenticarUsuarioContenidoResult->URL = "http://www.xtec.cat/error.html";
                        return $result;
                    }
                } else {
                    $usrcontent->Rol = "ESTUDIANTE";
                }
                //*********** FI
                if ($book_credential->success == 1) {
                    /// get the absolute book path
                    $path = $CFG->wwwroot . '/data/books/';
                    if ($usrcontent->IdUnidad == '' && $usrcontent->IdActividad == '') {
                        if (!($bookpath = get_record('books', 'isbn', $usrcontent->ISBN))) {
                            //save log error becouse the ISBN it's not found in db
                            add_to_log(1, '1-200', serialize(array('ISBN' => $usrcontent->ISBN)), true);
                        } else {
                            /// manipulate the manifest to set href's absolutes
                            if ($bookpath->format == 'scorm') {
                                if (!manifest_manipulation($bookpath->path)) {
                                    add_to_log(1, '1-201', serialize(array('ISBN' => $usrcontent->ISBN, 'path' => $bookpath->path)), true);
                                }
                            }
                            /// set the absolute path to the manifest
                            $result->AutenticarUsuarioContenidoResult->URL = $path . $bookpath->path;
                        }
                    } else {
                        if ($usrcontent->IdUnidad != '' && $usrcontent->IdActividad == '') {
                            if (!($bookpath = get_record('books', 'isbn', $usrcontent->ISBN))) {
                                //save log error becouse the ISBN it's not found in db
                                add_to_log(1, '1-210', serialize(array('ISBN' => $usrcontent->ISBN)), true);
                            } else {
                                if (!($unitpath = get_record('books_units', 'bookid', $bookpath->id, 'code', $usrcontent->IdUnidad))) {
                                    //save log error becouse the Unit code it's not found in db
                                    add_to_log(1, '1-211', serialize(array('ISBN' => $usrcontent->ISBN, 'unitcode' => $usrcontent->IdUnidad)), true);
                                    $result->AutenticarUsuarioContenidoResult->Codigo = "-5";
                                    $result->AutenticarUsuarioContenidoResult->Descripcion = "L'identificador de la unitat no &eacute;s v&agrave;lid";
                                    $result->AutenticarUsuarioContenidoResult->URL = "http://www.xtec.cat/error.html";
                                    return $result;
                                } else {
                                    /// manipulate the manifest to set href's absolutes
                                    if ($bookpath->format == 'scorm') {
                                        if (!manifest_manipulation($unitpath->path)) {
                                            add_to_log(1, '1-212', serialize(array('ISBN' => $usrcontent->ISBN, 'unitcode' => $usrcontent->IdUnidad, 'path' => $unitpath->path)), true);
                                        }
                                    }
                                    /// set the absolute path to the manifest
                                    $result->AutenticarUsuarioContenidoResult->URL = $path . $unitpath->path;
                                }
                            }
                        } else {
                            if ($usrcontent->IdUnidad != '' && $usrcontent->IdActividad != '') {
                                if (!($bookpath = get_record('books', 'isbn', $usrcontent->ISBN))) {
                                    //save log error becouse the ISBN it's not found in db
                                    add_to_log(1, '1-220', serialize(array('ISBN' => $usrcontent->ISBN)), true);
                                } else {
                                    if (!($unitpath = get_record('books_units', 'bookid', $bookpath->id, 'code', $usrcontent->IdUnidad))) {
                                        //save log error becouse the Unit code it's not found in db
                                        add_to_log(1, '1-221', serialize(array('ISBN' => $usrcontent->ISBN, 'unitcode' => $usrcontent->IdUnidad)), true);
                                        $result->AutenticarUsuarioContenidoResult->Codigo = "-5";
                                        $result->AutenticarUsuarioContenidoResult->Descripcion = "L'identificador de la unitat no &eacute;s v&agrave;lid";
                                        $result->AutenticarUsuarioContenidoResult->URL = "http://www.xtec.cat/error.html";
                                        return $result;
                                    } else {
                                        if (!($activitypath = get_record('books_activities', 'bookid', $bookpath->id, 'unitid', $unitpath->id, 'code', $usrcontent->IdActividad))) {
                                            add_to_log(1, '1-222', serialize(array('ISBN' => $usrcontent->ISBN, 'unitcode' => $usrcontent->IdUnidad, 'activitycode' => $usrcontent->IdActividad, 'path' => $activitypath->path)), true);
                                            $result->AutenticarUsuarioContenidoResult->Codigo = "-6";
                                            $result->AutenticarUsuarioContenidoResult->Descripcion = "L'identificador de la activitat no &eacute;s v&agrave;lid ";
                                            $result->AutenticarUsuarioContenidoResult->URL = "http://www.xtec.cat/error.html";
                                            return $result;
                                        } else {
                                            /// manipulate the manifest to set href's absolutes
                                            if ($bookpath->format == 'scorm') {
                                                if (!manifest_manipulation($activitypath->path)) {
                                                    add_to_log(1, '1-223', serialize(array('ISBN' => $usrcontent->ISBN, 'unitcode' => $usrcontent->IdUnidad, 'path' => $activitypath->path)), true);
                                                }
                                            }
                                            /// set the absolute path to the manifest
                                            $result->AutenticarUsuarioContenidoResult->URL = $path . $activitypath->path;
                                        }
                                    }
                                }
                            } else {
                                add_to_log(1, '1-204', serialize(array('ISBN' => $book_credencial->ISBN)));
                                $result->AutenticarUsuarioContenidoResult->URL = $book_credential->url;
                            }
                        }
                    }
                    //GAP
                    //********** AFEGIT XTEC - if URL generated correctly, generates the token and saves the data in the session table
                    if ($result->AutenticarUsuarioContenidoResult->Codigo == 1) {
                        if (isset($bookpath->format) and $bookpath->format == 'webcontent' and !isset($_GET['wsdl'])) {
                            $session = new stdClass();
                            $session->token = str_replace('.', '', uniqid('', true));
                            $session->isbn = $usrcontent->ISBN;
                            $session->userid = $usrcontent->IdUsuario;
                            $session->nameape = $usrcontent->NombreApe;
                            $session->groupid = $usrcontent->IdGrupo;
                            $session->courseid = $usrcontent->IdCurso;
                            $session->centerid = $usrcontent->IdCentro;
                            $session->wsurltracking = $usrcontent->URLResultado;
                            $session->lmscontentid = $usrcontent->IdContenidoLMS;
                            $session->unitid = $usrcontent->IdUnidad;
                            $session->activityid = $usrcontent->IdActividad;
                            $session->addtime = time();
                            $session->expiretime = time() + 86400;
                            //expire in 24 hours
                            $session->urlcontent = $result->AutenticarUsuarioContenidoResult->URL . "?token={$session->token}";
                            $session = addslashes_object($session);
                            $result->AutenticarUsuarioContenidoResult->URL = $result->AutenticarUsuarioContenidoResult->URL . "?token={$session->token}";
                            insert_record("sessions", $session);
                        }
                    }
                }
                //**********
            } else {
                $result->AutenticarUsuarioContenidoResult->Codigo = '-2';
                $result->AutenticarUsuarioContenidoResult->Descripcion = 'El codi de llicencia no es vàlid.';
                $result->AutenticarUsuarioContenidoResult->URL = 'http://www.xtec.cat/error.html';
            }
        } else {
            $result->AutenticarUsuarioContenidoResult->Codigo = '-3';
            $result->AutenticarUsuarioContenidoResult->Descripcion = 'El ISBN del producte no es vàlid.';
            $result->AutenticarUsuarioContenidoResult->URL = 'http://www.xtec.cat/error.html';
        }
    } else {
        $result->AutenticarUsuarioContenidoResult->Codigo = $auth->Codigo;
        $result->AutenticarUsuarioContenidoResult->Descripcion = $auth->Descripcion;
        $result->AutenticarUsuarioContenidoResult->URL = $auth->url;
    }
    /// save log registering method response
    add_to_log(1, 20, serialize($result->AutenticarUsuarioContenidoResult));
    return $result;
}
function glossary_restore_wiki2markdown($restore)
{
    global $CFG;
    $status = true;
    //Convert glossary_comments->entrycomment
    if ($records = get_records_sql("SELECT c.id, c.entrycomment, c.format\n                                         FROM {$CFG->prefix}glossary_comments c,\n                                              {$CFG->prefix}glossary_entries e,\n                                              {$CFG->prefix}glossary g,\n                                              {$CFG->prefix}backup_ids b\n                                         WHERE e.id = c.entryid AND\n                                               g.id = e.glossaryid AND\n                                               g.course = {$restore->course_id} AND\n                                               c.format = " . FORMAT_WIKI . " AND\n                                               b.backup_code = {$restore->backup_unique_code} AND\n                                               b.table_name = 'glossary_comments' AND\n                                               b.new_id = c.id")) {
        foreach ($records as $record) {
            //Rebuild wiki links
            $record->entrycomment = restore_decode_wiki_content($record->entrycomment, $restore);
            //Convert to Markdown
            $wtm = new WikiToMarkdown();
            $record->entrycomment = $wtm->convert($record->entrycomment, $restore->course_id);
            $record->format = FORMAT_MARKDOWN;
            $status = update_record('glossary_comments', addslashes_object($record));
            //Do some output
            $i++;
            if (($i + 1) % 1 == 0) {
                if (!defined('RESTORE_SILENTLY')) {
                    echo ".";
                    if (($i + 1) % 20 == 0) {
                        echo "<br />";
                    }
                }
                backup_flush(300);
            }
        }
    }
    //Convert glossary_entries->definition
    if ($records = get_records_sql("SELECT e.id, e.definition, e.format\n                                         FROM {$CFG->prefix}glossary_entries e,\n                                              {$CFG->prefix}glossary g,\n                                              {$CFG->prefix}backup_ids b\n                                         WHERE g.id = e.glossaryid AND\n                                               g.course = {$restore->course_id} AND\n                                               e.format = " . FORMAT_WIKI . " AND\n                                               b.backup_code = {$restore->backup_unique_code} AND\n                                               b.table_name = 'glossary_entries' AND\n                                               b.new_id = e.id")) {
        foreach ($records as $record) {
            //Rebuild wiki links
            $record->definition = restore_decode_wiki_content($record->definition, $restore);
            //Convert to Markdown
            $wtm = new WikiToMarkdown();
            $record->definition = $wtm->convert($record->definition, $restore->course_id);
            $record->format = FORMAT_MARKDOWN;
            $status = update_record('glossary_entries', addslashes_object($record));
            //Do some output
            $i++;
            if (($i + 1) % 1 == 0) {
                if (!defined('RESTORE_SILENTLY')) {
                    echo ".";
                    if (($i + 1) % 20 == 0) {
                        echo "<br />";
                    }
                }
                backup_flush(300);
            }
        }
    }
    return $status;
}
 $log->ActividadOrden = $result->ActividadOrden;
 $log->ActividadTitulo = $result->ActividadTitulo;
 $log->idUnidad = $result->idUnidad;
 $log->UnidadOrden = $result->UnidadOrden;
 $log->UnidadTitulo = $result->UnidadTitulo;
 $log->idCentro = $result->idCentro;
 $log->idContenidoLMS = $result->idContenidoLMS;
 $log->idUsuario = $result->idUsuario;
 $log->SumaPesos = $result->SumaPesos;
 $log->Duracion = $result->Resultado->Duracion;
 $log->FechaHoraInicio = $result->Resultado->FechaHoraInicio;
 $log->MaxDuracion = $result->Resultado->MaxDuracion;
 $log->Observaciones = $result->Resultado->Observaciones;
 $log->Calificacion = $result->Resultado->Calificacion;
 $log->URLVerResultados = $result->Resultado->URLVerResultados;
 add_to_log(3, 12, serialize(addslashes_object($log)));
 /// save log registering the number of details
 add_to_log(3, 13, serialize(count($result->Detalles)));
 $params = new ResultadoDetalleExtendido();
 $params->ResultadoExtendido = new SoapVar($result, SOAP_ENC_OBJECT, "SeguimientoExtendido", "http://educacio.gencat.cat/agora/seguimiento/");
 $client = new soapclient($reg_session->wsurltracking . '?wsdl', array('trace' => 1));
 $auth = array('User' => $reg_credential->username, 'Password' => $reg_credential->password);
 $namespace = rcommond_wdsl_parser($reg_session->wsurltracking . '?wsdl');
 $header = new SoapHeader($namespace, "WSEAuthenticateHeader", $auth);
 $client->__setSoapHeaders(array($header));
 /// save log registering the call to ws tracking
 add_to_log(3, 14);
 try {
     $response = $client->__soapCall("ResultadoDetalleExtendido", array($params));
 } catch (Exception $e) {
     print_r($e);
 function survey_copy($owner)
 {
     // clear the sid, clear the creation date, change the name, and clear the status
     // Since we're copying a data record, addslashes.
     $survey = addslashes_object($this->survey);
     unset($survey->id);
     $survey->owner = $owner;
     $survey->name .= '_copy';
     $survey->status = 0;
     // check for 'name' conflict, and resolve
     $i = 0;
     $name = $survey->name;
     while (count_records('questionnaire_survey', 'name', $name) > 0) {
         $name = $survey->name . ++$i;
     }
     if ($i) {
         $survey->name .= $i;
     }
     // create new survey
     if (!($new_sid = insert_record('questionnaire_survey', $survey))) {
         return false;
     }
     // make copies of all the questions
     $pos = 1;
     foreach ($this->questions as $question) {
         $tid = $question->type_id;
         $qid = $question->id;
         // fix some fields first
         unset($question->id);
         $question->survey_id = $new_sid;
         $question->position = $pos++;
         $question->name = addslashes($question->name);
         $question->content = addslashes($question->content);
         // copy question to new survey
         if (!($new_qid = insert_record('questionnaire_question', $question))) {
             return false;
         }
         foreach ($question->choices as $choice) {
             unset($choice->id);
             $choice->question_id = $new_qid;
             $choice->content = addslashes($choice->content);
             $choice->value = addslashes($choice->value);
             if (!insert_record('questionnaire_quest_choice', $choice)) {
                 return false;
             }
         }
     }
     return $new_sid;
 }
Beispiel #13
0
function restore_create_questions($restore, $xml_file)
{
    global $CFG, $db;
    $status = true;
    //Check it exists
    if (!file_exists($xml_file)) {
        $status = false;
    }
    //Get info from xml
    if ($status) {
        //info will contain the old_id of every category
        //in backup_ids->info will be the real info (serialized)
        $info = restore_read_xml_questions($restore, $xml_file);
    }
    //Now, if we have anything in info, we have to restore that
    //categories/questions
    if ($info) {
        if ($info !== true) {
            //Iterate over each category
            foreach ($info as $category) {
                //Skip empty categories (some backups can contain them)
                if (!empty($category->id)) {
                    $status = restore_question_categories($category, $restore);
                }
            }
            //Now we have to recode the parent field of each restored category
            $categories = get_records_sql("SELECT old_id, new_id \n                                               FROM {$CFG->prefix}backup_ids\n                                               WHERE backup_code = {$restore->backup_unique_code} AND\n                                                     table_name = 'question_categories'");
            if ($categories) {
                foreach ($categories as $category) {
                    $restoredcategory = get_record('question_categories', 'id', $category->new_id);
                    $restoredcategory = addslashes_object($restoredcategory);
                    if ($restoredcategory->parent != 0) {
                        $idcat = backup_getid($restore->backup_unique_code, 'question_categories', $restoredcategory->parent);
                        if ($idcat->new_id) {
                            $restoredcategory->parent = $idcat->new_id;
                        } else {
                            $restoredcategory->parent = 0;
                        }
                        update_record('question_categories', $restoredcategory);
                    }
                }
            }
        }
    } else {
        $status = false;
    }
    return $status;
}
/**
 * Adds or edits an existing calendar event for an assosciated meeting.
 *
 * There aqre two possible meeting configurations:
 * 1. A private meeting where only the people chosen to be particpants
 *    are allowed access.
 * 2. A public meeting where anyone in a given course is allowed to
 *    access to meeting.
 *
 * We must handle adding and removing users to a private meeting and also
 * deleteing unnecessary events when a meeting changes from private to
 * public and vice versa.
 *
 * @uses $CFG
 * @param int $meetingid The meeting ID to edit the calendar event for.
 * @param boolean $delete Whether the meeting is being deleted.
 * @return boolean True on success, False otherwise.
 */
function elluminate_cal_edit($meetingid, $delete = false)
{
    global $CFG;
    if (!($meeting = get_record('elluminate', 'id', $meetingid))) {
        return false;
    }
    /// Special action if we're deleting a meeting.
    if ($delete) {
        if ($events = elluminate_get_events($meeting->id)) {
            foreach ($events as $event) {
                delete_records('event', 'id', $event->id);
            }
        }
        return true;
    }
    if ($meeting->private) {
        /// If this meeting has been newly marked private, delete the old, public,
        /// event record.
        $admin = get_admin();
        $sql = "DELETE FROM {$CFG->prefix}event\n\t\t\t\t\t\t\t\t                    WHERE modulename = 'elluminate'\n\t\t\t\t\t\t\t\t                    AND instance = {$meeting->id}\n\t\t\t\t\t\t\t\t                    AND courseid = {$meeting->course}\n\t\t\t\t\t\t\t\t                    AND userid = {$admin->id}";
        execute_sql($sql, false);
    } else {
        if (!$meeting->private && !elluminate_has_course_event($meeting->id)) {
            /// Create the new course event.
            $admin = get_admin();
            $event = new stdClass();
            $event->name = get_string('calendarname', 'elluminate', $meeting->name);
            $event->description = $meeting->description;
            $event->format = 1;
            $event->courseid = $meeting->course;
            $event->groupid = 0;
            $event->userid = $admin->id;
            $event->modulename = 'elluminate';
            $event->instance = $meeting->id;
            $event->eventtype = '';
            $event->visible = 1;
            $event->timestart = $meeting->timestart;
            $duration = $meeting->timeend - $meeting->timestart;
            if ($duration < 0) {
                $event->timeduration = 0;
            } else {
                $event->timeduration = $duration;
            }
            $event->timemodified = time();
            $event = addslashes_object($event);
            $event->id = insert_record('event', $event);
            return true;
        }
    }
    if (!($elluminate = get_record("elluminate", "id", $meetingid))) {
        error("Course module is incorrect");
    }
    if (!($course = get_record("course", "id", $elluminate->course))) {
        error("Course is misconfigured");
    }
    if (!($cm = get_coursemodule_from_instance("elluminate", $elluminate->id, $course->id))) {
        error("Course Module ID was incorrect");
    }
    /// Modifying any existing events.
    if ($events = elluminate_get_events($meeting->id)) {
        foreach ($events as $event) {
            /// Delete any non-moderator events if this meeting is public...
            $deleted = false;
            if (empty($meeting->private) && empty($event->userid)) {
                if ($elm_id = get_field('elluminate_users', 'elm_id', 'userid', $event->userid)) {
                    if (!has_capability('mod/elluminate:moderatemeeting', $context, $USER->id, false)) {
                        $deleted = delete_records('event', 'id', $event->id);
                    }
                }
            }
            if (!$deleted) {
                $event->name = addslashes(get_string('calendarname', 'elluminate', $meeting->name));
                $event->description = addslashes($meeting->description);
                $event->timestart = $meeting->timestart;
                $duration = $meeting->timeend - $meeting->timestart;
                if ($duration < 0) {
                    $event->timeduration = 0;
                } else {
                    $event->timeduration = $duration;
                }
                $eventtimemodified = time();
                if (!update_record('event', $event)) {
                    return false;
                }
            }
        }
    }
    return true;
}
Beispiel #15
0
function forum_restore_wiki2markdown($restore)
{
    global $CFG;
    $status = true;
    //Convert forum_posts->message
    if ($records = get_records_sql("SELECT p.id, p.message, p.format\n                                         FROM {$CFG->prefix}forum_posts p,\n                                              {$CFG->prefix}forum_discussions d,\n                                              {$CFG->prefix}forum f,\n                                              {$CFG->prefix}backup_ids b\n                                         WHERE d.id = p.discussion AND\n                                               f.id = d.forum AND\n                                               f.course = {$restore->course_id} AND\n                                               p.format = " . FORMAT_WIKI . " AND\n                                               b.backup_code = {$restore->backup_unique_code} AND\n                                               b.table_name = 'forum_posts' AND\n                                               b.new_id = p.id")) {
        foreach ($records as $record) {
            //Rebuild wiki links
            $record->message = restore_decode_wiki_content($record->message, $restore);
            //Convert to Markdown
            $wtm = new WikiToMarkdown();
            $record->message = $wtm->convert($record->message, $restore->course_id);
            $record->format = FORMAT_MARKDOWN;
            $status = update_record('forum_posts', addslashes_object($record));
            //Do some output
            $i++;
            if (($i + 1) % 1 == 0) {
                if (!defined('RESTORE_SILENTLY')) {
                    echo ".";
                    if (($i + 1) % 20 == 0) {
                        echo "<br />";
                    }
                }
                backup_flush(300);
            }
        }
    }
    return $status;
}
}
/// Make a recording visible to only group members.
if (!empty($hidegrouprecording) && $groupmode == VISIBLEGROUPS && ($canmanageanyrecordings || $canmanagerecordings)) {
    if ($recording = get_record('elluminate_recordings', 'id', $hidegrouprecording)) {
        $recording->groupvisible = 0;
        $recording = addslashes_object($recording);
        if (!update_record('elluminate_recordings', $recording)) {
            debugging('Unable to change recording group visibility!');
        }
    }
}
/// Make a recording visible to only group members.
if (!empty($showgrouprecording) && $groupmode == VISIBLEGROUPS && ($canmanageanyrecordings || $canmanagerecordings)) {
    if ($recording = get_record('elluminate_recordings', 'id', $showgrouprecording)) {
        $recording->groupvisible = 1;
        $recording = addslashes_object($recording);
        if (!update_record('elluminate_recordings', $recording)) {
            debugging('Unable to hide recording!');
        }
    }
}
add_to_log($course->id, "elluminate", "view", "view.php?id={$cm->id}", "{$elluminate->id}");
if ($groupmode) {
    if (!empty($currentgroup)) {
        if (!empty($elluminate->customname)) {
            $elluminate->name = $elluminate->name . ' - ' . $course->shortname . ' - ' . $groupname;
        }
        if (!empty($elluminate->customdescription)) {
            $elluminate->description = $groupname . ' - ' . $elluminate->description;
        }
    }
 $podcast_item->title = $form->title;
 $podcast_item->lien = $form->lien;
 $podcast_item->intro = $form->intro;
 $podcast_item->pubdate = $form->pubdate;
 $podcast_item->date_html = $form->date_html;
 $podcast_item->duration = $form->duration;
 $podcast_item->length = $form->length;
 // V�rification et insertion dans la base
 $erreur = 0;
 if (!check_podcast_extension($podcast_item->lien)) {
     $erreur = 1;
 }
 if (trim($podcast_item->title) == "") {
     $erreur = 2;
 }
 switch ($erreur) {
     case 0:
         if (update_record("podcast_structure", addslashes_object($podcast_item))) {
             unset($form);
             $tab = "view";
             echo "<p style='color:green;text-align:center;margin:0;font-size:0.8em;font-weight:bold;'>" . get_string('update_ok', 'podcast') . "</p>";
             // XML
             if (make_xml_podcast($podcast)) {
                 echo "<p style='color:green;text-align:center;margin:0;font-size:0.8em;font-weight:bold;'>" . get_string('xml_ok', 'podcast') . "</p>";
             } else {
                 echo "<p style='color:red;text-align:center;margin:0;font-size:0.8em;font-weight:bold;'>" . get_string('xml_error', 'podcast') . "</p>";
             }
         } else {
             $tab = "add";
             echo "<p style='color:red;text-align:center;margin:0;font-size:0.8em;font-weight:bold;'>" . get_string('errordb', 'podcast') . "</p>";
         }
Beispiel #18
0
function certificate_issue($course, $certificate, $certrecord, $cm)
{
    if ($certificate->printgrade > 0) {
        if ($certificate->printgrade == 1) {
            $grade = certificate_print_course_grade($course);
        } else {
            if ($certificate->printgrade > 1) {
                $grade = certificate_print_mod_grade($course, $certificate->printgrade);
            }
        }
        if ($certificate->gradefmt == 1) {
            $certrecord->reportgrade = addslashes($grade->percentage);
        }
        if ($certificate->gradefmt == 2) {
            $certrecord->reportgrade = addslashes($grade->points);
        }
        if ($certificate->gradefmt == 3) {
            $certrecord->reportgrade = addslashes($grade->letter);
        }
    }
    $date = certificate_generate_date($certificate, $course);
    $certrecord->certdate = $date;
    update_record('certificate_issues', addslashes_object($certrecord));
    certificate_email_teachers($course, $certificate, $certrecord, $cm);
    certificate_email_others($course, $certificate, $certrecord, $cm);
}
Beispiel #19
0
 /**
 * Process the person tag. This defines a Moodle user.
 * @param string $tagconents The raw contents of the XML element
 */
 function process_person_tag($tagcontents)
 {
     global $CFG;
     if (preg_match('{<sourcedid>.*?<id>(.+?)</id>.*?</sourcedid>}is', $tagcontents, $matches)) {
         $person->idnumber = trim($matches[1]);
     }
     if (preg_match('{<name>.*?<n>.*?<given>(.+?)</given>.*?</n>.*?</name>}is', $tagcontents, $matches)) {
         $person->firstname = trim($matches[1]);
     }
     if (preg_match('{<name>.*?<n>.*?<family>(.+?)</family>.*?</n>.*?</name>}is', $tagcontents, $matches)) {
         $person->lastname = trim($matches[1]);
     }
     if (preg_match('{<userid>(.*?)</userid>}is', $tagcontents, $matches)) {
         $person->username = trim($matches[1]);
     }
     if ($CFG->enrol_imssourcedidfallback && trim($person->username) == '') {
         // This is the point where we can fall back to useing the "sourcedid" if "userid" is not supplied
         // NB We don't use an "elseif" because the tag may be supplied-but-empty
         $person->username = $person->idnumber;
     }
     if (preg_match('{<email>(.*?)</email>}is', $tagcontents, $matches)) {
         $person->email = trim($matches[1]);
     }
     if (preg_match('{<url>(.*?)</url>}is', $tagcontents, $matches)) {
         $person->url = trim($matches[1]);
     }
     if (preg_match('{<adr>.*?<locality>(.+?)</locality>.*?</adr>}is', $tagcontents, $matches)) {
         $person->city = trim($matches[1]);
     }
     if (preg_match('{<adr>.*?<country>(.+?)</country>.*?</adr>}is', $tagcontents, $matches)) {
         $person->country = trim($matches[1]);
     }
     // Fix case of some of the fields if required
     if ($CFG->enrol_fixcaseusernames && isset($person->username)) {
         $person->username = strtolower($person->username);
     }
     if ($CFG->enrol_fixcasepersonalnames) {
         if (isset($person->firstname)) {
             $person->firstname = ucwords(strtolower($person->firstname));
         }
         if (isset($person->lastname)) {
             $person->lastname = ucwords(strtolower($person->lastname));
         }
     }
     $recstatus = $this->get_recstatus($tagcontents, 'person');
     // Now if the recstatus is 3, we should delete the user if-and-only-if the setting for delete users is turned on
     // In the "users" table we can do this by setting deleted=1
     if ($recstatus == 3) {
         if ($CFG->enrol_imsdeleteusers) {
             // If we're allowed to delete user records
             // Make sure their "deleted" field is set to one
             set_field('user', 'deleted', 1, 'username', $person->username);
             $this->log_line("Marked user record for user '{$person->username}' (ID number {$person->idnumber}) as deleted.");
         } else {
             $this->log_line("Ignoring deletion request for user '{$person->username}' (ID number {$person->idnumber}).");
         }
     } else {
         // Add or update record
         // If the user exists (matching sourcedid) then we don't need to do anything.
         if (!get_field('user', 'id', 'idnumber', $person->idnumber) && $CFG->enrol_createnewusers) {
             // If they don't exist and haven't a defined username, we log this as a potential problem.
             if (!isset($person->username) || strlen($person->username) == 0) {
                 $this->log_line("Cannot create new user for ID # {$person->idnumber} - no username listed in IMS data for this person.");
             } elseif (get_field('user', 'id', 'username', $person->username)) {
                 // If their idnumber is not registered but their user ID is, then add their idnumber to their record
                 set_field('user', 'idnumber', addslashes($person->idnumber), 'username', $person->username);
             } else {
                 // If they don't exist and they have a defined username, and $CFG->enrol_createnewusers == true, we create them.
                 $person->lang = 'manual';
                 //TODO: this needs more work due tu multiauth changes
                 $person->auth = $CFG->auth;
                 $person->confirmed = 1;
                 $person->timemodified = time();
                 $person->mnethostid = $CFG->mnet_localhost_id;
                 if ($id = insert_record('user', addslashes_object($person))) {
                     /*
                     Photo processing is deactivated until we hear from Moodle dev forum about modification to gdlib.
                     
                                                  //Antoni Mas. 07/12/2005. If a photo URL is specified then we might want to load
                                                  // it into the user's profile. Beware that this may cause a heavy overhead on the server.
                                                  if($CFG->enrol_processphoto){
                                                    if(preg_match('{<photo>.*?<extref>(.*?)</extref>.*?</photo>}is', $tagcontents, $matches)){
                                                      $person->urlphoto = trim($matches[1]);
                                                    }
                                                    //Habilitam el flag que ens indica que el personatge t foto prpia.
                                                    $person->picture = 1;
                                                    //Llibreria creada per nosaltres mateixos.
                                                    require_once($CFG->dirroot.'/lib/gdlib.php');
                                                    if ($usernew->picture = save_profile_image($id, $person->urlphoto,'user')) {
                                                      set_field('user', 'picture', $usernew->picture, 'id', $id);  /// Note picture in DB
                                                    }
                                                  }
                     */
                     $this->log_line("Created user record for user '{$person->username}' (ID number {$person->idnumber}).");
                 } else {
                     $this->log_line("Database error while trying to create user record for user '{$person->username}' (ID number {$person->idnumber}).");
                 }
             }
         } elseif ($CFG->enrol_createnewusers) {
             $this->log_line("User record already exists for user '{$person->username}' (ID number {$person->idnumber}).");
             // Make sure their "deleted" field is set to zero.
             set_field('user', 'deleted', 0, 'idnumber', $person->idnumber);
         } else {
             $this->log_line("No user record found for '{$person->username}' (ID number {$person->idnumber}).");
         }
     }
     // End of are-we-deleting-or-adding
 }
Beispiel #20
0
 /**
 * Prints the entry form/page for this enrolment
 *
 * This is only called from course/enrol.php
 * Most plugins will probably override this to print payment ...
 *
 * @param    course  current course object
 */
 function print_entry($course)
 {
     global $CFG, $USER, $SESSION, $THEME, $SITE;
     $strloginto = get_string('loginto', '', $course->shortname);
     $strcourses = get_string('courses');
     $context = get_context_instance(CONTEXT_SYSTEM);
     $navlinks = array();
     $navlinks[] = array('name' => $strcourses, 'link' => ".", 'type' => 'misc');
     $navlinks[] = array('name' => $strloginto, 'link' => null, 'type' => 'misc');
     $navigation = build_navigation($navlinks);
     if (has_capability('moodle/legacy:guest', $context, $USER->id, false)) {
         add_to_log($course->id, 'course', 'guest', 'view.php?id=' . $course->id, getremoteaddr());
         return;
     }
     if (empty($_GET['confirm']) && empty($_GET['cancel'])) {
         print_header($strloginto, $course->fullname, $navigation);
         echo '<br />';
         notice_yesno(get_string('enrolmentrequest', 'enrol_moderated'), "enrol.php?id={$course->id}&amp;confirm=1", "enrol.php?id={$course->id}&amp;cancel=1");
         print_footer();
         return;
     }
     if (!empty($_GET['confirm'])) {
         print_header($strloginto, $course->fullname, $navigation);
         print_box(get_string('application', 'enrol_moderated'));
         print_continue($CFG->wwwroot, $return = false);
         print_footer();
         // Send email to student
         $a->site = $SITE->shortname;
         $a->course = $course->shortname;
         $subject = get_string('applicationsubject', 'enrol_moderated', $a);
         $body = get_string('applicationbody', 'enrol_moderated');
         email_to_user($USER, $SITE->shortname, $subject, $body);
         // Send email to admin
         $a->url = $CFG->wwwroot . '/enrol/moderated/show_requests.php';
         $a->user = $USER->username;
         $body = get_string('applicationadminbody', 'enrol_moderated', $a);
         if (isset($CFG->enrol_moderated_moderatoremail)) {
             $dest->email = $CFG->enrol_moderated_moderatoremail;
         } else {
             $dest = get_admin();
         }
         email_to_user($dest, $SITE->shortname, $subject, $body);
         // Check if user has already requested enrolment for the same course
         if (!get_record('enrol_moderated', 'userid', $USER->id, 'courseid', $course->id)) {
             // Create db entry
             $data = new object();
             $data->courseid = $course->id;
             $data->userid = $USER->id;
             $data->created = time();
             $data->updated = time();
             $data->status = 0;
             // pending
             insert_record('enrol_moderated', addslashes_object($data), false);
         }
         return;
     }
     if (!empty($_GET['cancel'])) {
         unset($SESSION->wantsurl);
         if (!empty($SESSION->enrolcancel)) {
             $destination = $SESSION->enrolcancel;
             unset($SESSION->enrolcancel);
         } else {
             $destination = $CFG->wwwroot;
         }
         redirect($destination);
     }
 }
 function replace_keys()
 {
     global $CFG;
     $this->keypair = array();
     $this->keypair = mnet_generate_keypair();
     $this->public_key = $this->keypair['certificate'];
     $this->wwwroot = $CFG->wwwroot;
     $details = openssl_x509_parse($this->public_key);
     $this->public_key_expires = $details['validTo_time_t'];
     if (empty($_SERVER['SERVER_ADDR'])) {
         // SERVER_ADDR is only returned by Apache-like webservers
         $my_hostname = mnet_get_hostname_from_uri($CFG->wwwroot);
         $my_ip = gethostbyname($my_hostname);
         // Returns unmodified hostname on failure. DOH!
         if ($my_ip == $my_hostname) {
             $this->ip_address = 'UNKNOWN';
         } else {
             $this->ip_address = $my_ip;
         }
     } else {
         $this->ip_address = $_SERVER['SERVER_ADDR'];
     }
     set_config('openssl', implode('@@@@@@@@', $this->keypair), 'mnet');
     // clone the proper object and then unset anything that isn't required to go into the database
     // most fields don't matter but things that are arrays, will break things.
     $dbobject = (object) clone $this;
     unset($dbobject->keypair);
     update_record('mnet_host', addslashes_object($dbobject));
     error_log('New public key has been generated. It expires ' . date('Y/m/d h:i:s', $this->public_key_expires));
 }
Beispiel #22
0
 /**
  * Receives an array of log entries from an SP and adds them to the mnet_log
  * table
  *
  * @param   array   $array      An array of usernames
  * @return  string              "All ok" or an error message
  */
 function refresh_log($array)
 {
     global $CFG, $MNET_REMOTE_CLIENT;
     // We don't want to output anything to the client machine
     $start = ob_start();
     $returnString = '';
     begin_sql();
     $useridarray = array();
     foreach ($array as $logEntry) {
         $logEntryObj = (object) $logEntry;
         $logEntryObj->hostid = $MNET_REMOTE_CLIENT->id;
         if (isset($useridarray[$logEntryObj->username])) {
             $logEntryObj->userid = $useridarray[$logEntryObj->username];
         } else {
             $logEntryObj->userid = get_field('user', 'id', 'username', $logEntryObj->username);
             if ($logEntryObj->userid == false) {
                 $logEntryObj->userid = 0;
             }
             $useridarray[$logEntryObj->username] = $logEntryObj->userid;
         }
         unset($logEntryObj->username);
         $insertok = insert_record('mnet_log', addslashes_object($logEntryObj), false);
         if ($insertok) {
             $MNET_REMOTE_CLIENT->last_log_id = $logEntryObj->remoteid;
         } else {
             $returnString .= 'Record with id ' . $logEntryObj->remoteid . " failed to insert.\n";
         }
     }
     $MNET_REMOTE_CLIENT->commit();
     commit_sql();
     $end = ob_end_clean();
     if (empty($returnString)) {
         return array('code' => 0, 'message' => 'All ok');
     }
     return array('code' => 1, 'message' => $returnString);
 }
Beispiel #23
0
 function create_course($course, $skip_fix_course_sortorder = 0)
 {
     global $CFG;
     // define a template
     if (!empty($CFG->enrol_db_template)) {
         $template = get_record("course", 'shortname', $CFG->enrol_db_template);
         $template = (array) $template;
     } else {
         $site = get_site();
         $template = array('startdate' => time() + 3600 * 24, 'summary' => get_string("defaultcoursesummary"), 'format' => "weeks", 'password' => "", 'guest' => 0, 'numsections' => 10, 'idnumber' => '', 'cost' => '', 'newsitems' => 5, 'showgrades' => 1, 'groupmode' => 0, 'groupmodeforce' => 0, 'student' => $site->student, 'students' => $site->students, 'teacher' => $site->teacher, 'teachers' => $site->teachers);
     }
     // overlay template
     foreach (array_keys($template) as $key) {
         if (empty($course->{$key})) {
             $course->{$key} = $template[$key];
         }
     }
     $course->category = 1;
     // the misc 'catch-all' category
     if (!empty($CFG->enrol_db_category)) {
         //category = 0 or undef will break moodle
         $course->category = $CFG->enrol_db_category;
     }
     // define the sortorder
     $sort = get_field_sql('SELECT COALESCE(MAX(sortorder)+1, 100) AS max ' . ' FROM ' . $CFG->prefix . 'course ' . ' WHERE category=' . $course->category);
     $course->sortorder = $sort;
     // override with local data
     $course->startdate = time() + 3600 * 24;
     $course->timecreated = time();
     $course->visible = 1;
     // clear out id just in case
     unset($course->id);
     // truncate a few key fields
     $course->idnumber = substr($course->idnumber, 0, 100);
     $course->shortname = substr($course->shortname, 0, 100);
     // store it and log
     if ($newcourseid = insert_record("course", addslashes_object($course))) {
         // Set up new course
         $section = NULL;
         $section->course = $newcourseid;
         // Create a default section.
         $section->section = 0;
         $section->id = insert_record("course_sections", $section);
         $page = page_create_object(PAGE_COURSE_VIEW, $newcourseid);
         blocks_repopulate_page($page);
         // Return value no
         if (!$skip_fix_course_sortorder) {
             fix_course_sortorder();
         }
         add_to_log($newcourseid, "course", "new", "view.php?id={$newcourseid}", "enrol/database auto-creation");
     } else {
         trigger_error("Could not create new course {$extcourse} from  from database");
         notify("Serious Error! Could not create the new course!");
         return false;
     }
     return $newcourseid;
 }
Beispiel #24
0
/**
 * Moves unread messages from message table to message_read for a given from user
 * @param object $userid       User id
 * @return boolean success
 */
function message_move_userfrom_unread2read($userid)
{
    // move all unread messages from message table to messasge_read
    if ($messages = get_records_select('message', "useridfrom = {$userid}", 'timecreated')) {
        foreach ($messages as $message) {
            $message->timeread = 0;
            //the message was never read
            $message = addslashes_object($message);
            $messageid = $message->id;
            unset($message->id);
            if (insert_record('message_read', $message)) {
                delete_records('message', 'id', $messageid);
            } else {
                return false;
            }
        }
    }
    return true;
}
Beispiel #25
0
 $authplugin = get_auth_plugin($user->auth);
 $usernew->timemodified = time();
 $usernew->username = get_field('user', 'username', 'id', $usernew->id);
 // not in the edit form of the user
 // Added: to call calendar ws to edit user.
 if (modifyQSUser($usernew)) {
     $olduserinfo = get_record('user', 'id', $usernew->id);
     if (editUserProfile($usernew->username, $usernew)) {
         if (!update_record('user', $usernew)) {
             admin_moodlefailed_email($usernew, 'modifyUser');
             error('Error updating user record');
         }
         // pass a true $userold here
         if (!$authplugin->user_update($user, $userform->get_data(false))) {
             // auth update failed, rollback for moodle
             update_record('user', addslashes_object($user));
             error('Failed to update user data on external auth: ' . $user->auth . '. See the server logs for more details.');
         }
         //update preferences
         useredit_update_user_preference($usernew);
         //update interests
         if (!empty($CFG->usetags)) {
             useredit_update_interests($usernew, $usernew->interests);
         }
         //update user picture
         if (!empty($CFG->gdversion) and empty($CFG->disableuserimages)) {
             useredit_update_picture($usernew, $userform);
         }
         // update mail bounces
         useredit_update_bounces($user, $usernew);
         /// update forum track preference
$navlinks[] = array('name' => $strilp, 'link' => "{$CFG->wwwroot}/blocks/ilp/view.php?id={$user->id}&amp;courseid={$courseid}", 'type' => 'misc');
$navlinks[] = array('name' => fullname($user), 'link' => FALSE, 'type' => 'misc');
$navlinks[] = array('name' => $strtargets, 'link' => FALSE, 'type' => 'misc');
$navigation = build_navigation($navlinks);
print_header_simple($title, '', $navigation, '', '', true, '', '');
//Allow users to see their own profile, but prevent others
if (has_capability('moodle/legacy:guest', $context, NULL, false)) {
    error("You are logged in as Guest.");
}
if ($action == 'updatestatus') {
    require_once "{$CFG->dirroot}/message/lib.php";
    $report = get_record('ilptarget_posts', 'id', $targetpost);
    // Get or make one
    $report->status = $status;
    $report->timemodified = time();
    update_record('ilptarget_posts', addslashes_object($report));
    if ($CFG->ilptarget_send_target_message == 1) {
        switch ($status) {
            case "0":
                $thistargetstatus = get_string('outstanding', 'ilptarget');
                break;
            case "1":
                $thistargetstatus = get_string('achieved', 'ilptarget');
                break;
                //case "2":
                //$thistargetstatus = get_string('notachieved', 'ilptarget');
                //break;
            //case "2":
            //$thistargetstatus = get_string('notachieved', 'ilptarget');
            //break;
            case "3":
Beispiel #27
0
function assignment_restore_wiki2markdown($restore)
{
    global $CFG;
    $status = true;
    //Convert assignment->description
    if ($records = get_records_sql("SELECT a.id, a.description, a.format\n                                         FROM {$CFG->prefix}assignment a,\n                                              {$CFG->prefix}backup_ids b\n                                         WHERE a.course = {$restore->course_id} AND\n                                               a.format = " . FORMAT_WIKI . " AND\n                                               b.backup_code = {$restore->backup_unique_code} AND\n                                               b.table_name = 'assignment' AND\n                                               b.new_id = a.id")) {
        foreach ($records as $record) {
            //Rebuild wiki links
            $record->description = restore_decode_wiki_content($record->description, $restore);
            //Convert to Markdown
            $wtm = new WikiToMarkdown();
            $record->description = $wtm->convert($record->description, $restore->course_id);
            $record->format = FORMAT_MARKDOWN;
            $status = update_record('assignment', addslashes_object($record));
            //Do some output
            $i++;
            if (($i + 1) % 1 == 0) {
                if (!defined('RESTORE_SILENTLY')) {
                    echo ".";
                    if (($i + 1) % 20 == 0) {
                        echo "<br />";
                    }
                }
                backup_flush(300);
            }
        }
    }
    return $status;
}
 /**
  * import()
  * TODO document
  */
 function import()
 {
     global $CFG;
     list($settings, $newfields, $currentfields) = $this->load_from_file();
     $preservedfields = array();
     /* Maps fields and makes new ones */
     if (!empty($newfields)) {
         /* We require an injective mapping, and need to know what to protect */
         foreach ($newfields as $nid => $newfield) {
             $cid = optional_param("field_{$nid}", -1, PARAM_INT);
             if ($cid == -1) {
                 continue;
             }
             if (array_key_exists($cid, $preservedfields)) {
                 print_error('notinjectivemap', 'data');
             } else {
                 $preservedfields[$cid] = true;
             }
         }
         foreach ($newfields as $nid => $newfield) {
             $cid = optional_param("field_{$nid}", -1, PARAM_INT);
             /* A mapping. Just need to change field params. Data kept. */
             if ($cid != -1 and isset($currentfelds[$cid])) {
                 $fieldobject = data_get_field_from_id($currentfields[$cid]->id, $this->data);
                 foreach ($newfield as $param => $value) {
                     if ($param != "id") {
                         $fieldobject->field->{$param} = $value;
                     }
                 }
                 unset($fieldobject->field->similarfield);
                 $fieldobject->update_field();
                 unset($fieldobject);
             } else {
                 include_once "field/{$newfield->type}/field.class.php";
                 if (!isset($newfield->description)) {
                     $newfield->description = '';
                 }
                 $classname = 'data_field_' . $newfield->type;
                 $fieldclass = new $classname($newfield, $this->data);
                 $fieldclass->insert_field();
                 unset($fieldclass);
             }
         }
     }
     /* Get rid of all old unused data */
     if (!empty($preservedfields)) {
         foreach ($currentfields as $cid => $currentfield) {
             if (!array_key_exists($cid, $preservedfields)) {
                 /* Data not used anymore so wipe! */
                 print "Deleting field {$currentfield->name}<br />";
                 $id = $currentfield->id;
                 // Why delete existing data records and related comments/ratings ??
                 /*
                 if ($content = get_records('data_content', 'fieldid', $id)) {
                     foreach ($content as $item) {
                         delete_records('data_ratings', 'recordid', $item->recordid);
                         delete_records('data_comments', 'recordid', $item->recordid);
                         delete_records('data_records', 'id', $item->recordid);
                     }
                 }
                 */
                 delete_records('data_content', 'fieldid', $id);
                 delete_records('data_fields', 'id', $id);
             }
         }
     }
     data_update_instance(addslashes_object($settings));
     if (strstr($this->directory, '/temp/')) {
         clean_preset($this->directory);
     }
     /* Removes the temporary files */
     return true;
 }
Beispiel #29
0
@ob_implicit_flush(true);
@ob_end_flush();
if ($messages = get_records_select('message', "useridto = '{$USER->id}' AND useridfrom = '{$userid}'", 'timecreated')) {
    foreach ($messages as $message) {
        $time = userdate($message->timecreated, get_string('strftimedatetimeshort'));
        $options = new object();
        $options->para = false;
        $options->newlines = true;
        $printmessage = format_text($message->message, $message->format, $options);
        $printmessage = '<div class="message other"><span class="author">' . s($userfullname) . '</span> ' . '<span class="time">[' . $time . ']</span>: ' . '<span class="content">' . $printmessage . '</span></div>';
        $printmessage = addslashes_js($printmessage);
        // So Javascript can write it
        echo "parent.messages.document.write('" . $printmessage . "');\n";
        /// Move the entry to the other table
        $message->timeread = time();
        $message = addslashes_object($message);
        $messageid = $message->id;
        unset($message->id);
        if (insert_record('message_read', $message)) {
            delete_records('message', 'id', $messageid);
        }
    }
    if (get_user_preferences('message_beepnewmessage', 0)) {
        $playbeep = true;
    }
    echo 'parent.messages.scroll(1,5000000);' . "\n";
    echo 'parent.send.focus();' . "\n";
    $wait = MESSAGE_DEFAULT_REFRESH;
} else {
    if ($wait < 300) {
        // Until the wait is five minutes
Beispiel #30
0
function xmldb_block_curr_admin_upgrade($oldversion = 0)
{
    global $CFG, $THEME, $db;
    $result = true;
    if ($oldversion < 2009010102) {
        $context = get_context_instance(CONTEXT_SYSTEM, SITEID);
        if ($role = get_record('role', 'shortname', 'curriculumadmin')) {
            if ($role->name == 'Bundle Administrator') {
                $role->name = 'Curriculum Administrator';
                addslashes_object($role);
                update_record('role', $role);
            }
        }
        if (!empty($role->id)) {
            require_once dirname(__FILE__) . '/access.php';
            if (!empty($block_curr_admin_capabilities)) {
                foreach ($block_curr_admin_capabilities as $capname => $caprules) {
                    $result = $result && assign_capability($capname, CAP_ALLOW, $role->id, $context->id);
                }
            }
        }
    }
    if ($oldversion < 2009010103) {
        $table = new XMLDBTable('crlm_curriculum');
        $field = new XMLDBField('timetocomplete');
        $field->setAttributes(XMLDB_TYPE_CHAR, '64', NULL, XMLDB_NOTNULL, NULL, NULL, NULL, '0h, 0d, 0w, 0m, 0y', 'timemodified');
        $result = $result && add_field($table, $field);
        $field = new XMLDBField('frequency');
        $field->setAttributes(XMLDB_TYPE_CHAR, '64', NULL, XMLDB_NOTNULL, NULL, NULL, NULL, '0h, 0d, 0w, 0m, 0y', 'timetocomplete');
        $result = $result && add_field($table, $field);
    }
    if ($oldversion < 2009010104) {
        $table = new XMLDBTable('crlm_config');
        $table->comment = 'Curriculum management configuration values.';
        // fields
        $f = $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', false, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $f = $table->addFieldInfo('name', XMLDB_TYPE_CHAR, '255', null, false, null, null, null, null);
        $f = $table->addFieldInfo('value', XMLDB_TYPE_TEXT, 'medium', null, false, null, null, null, null);
        // PK and indexes
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addIndexInfo('name_ix', XMLDB_INDEX_UNIQUE, array('name'));
        $result = $result && create_table($table);
    }
    if ($oldversion < 2009010105) {
        $table = new XMLDBTable('crlm_coursetemplate');
        $table->comment = 'Course templates';
        // fields
        $f = $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', false, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $f = $table->addFieldInfo('courseid', XMLDB_TYPE_INTEGER, '10', false, XMLDB_NOTNULL, null, null, null, null);
        $f = $table->addFieldInfo('location', XMLDB_TYPE_CHAR, '255', null, false, null, null, null, null);
        $f = $table->addFieldInfo('templateclass', XMLDB_TYPE_CHAR, '255', null, false, null, null, null, null);
        // PK and indexes
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addIndexInfo('courseid_ix', XMLDB_INDEX_UNIQUE, array('courseid'));
        $result = $result && create_table($table);
    }
    if ($oldversion < 2009010106) {
        $table = new XMLDBTable('crlm_cluster_curriculum');
        $table->comment = 'Association between clusters and curricula';
        // fields
        $f = $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', false, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $f = $table->addFieldInfo('clusterid', XMLDB_TYPE_INTEGER, '10', null, true, null, null, null, null, 'id');
        $f->comment = 'Foreign key to cluster id';
        $f = $table->addFieldInfo('curriculumid', XMLDB_TYPE_INTEGER, '10', null, true, null, null, null, null, 'clusterid');
        $f->comment = 'Foreign key to curriculum id';
        // PK and indexes
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addIndexInfo('cluster_idx', XMLDB_INDEX_NOTUNIQUE, array('clusterid'));
        $result = $result && create_table($table);
    }
    if ($oldversion < 2009010108) {
        $table = new XMLDBTable('crlm_cluster_track');
        $table->comment = 'Association between clusters and tracks';
        // fields
        $f = $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', false, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $f = $table->addFieldInfo('clusterid', XMLDB_TYPE_INTEGER, '10', null, true, null, null, null, null, 'id');
        $f->comment = 'Foreign key to cluster id';
        $f = $table->addFieldInfo('trackid', XMLDB_TYPE_INTEGER, '10', null, true, null, null, null, null, 'clusterid');
        $f->comment = 'Foreign key to track id';
        $f = $table->addFieldInfo('autounenrol', XMLDB_TYPE_INTEGER, '1', null, true, null, null, null, null, 'trackid');
        $f->comment = 'Whether or not to remove a user from classes when removed from cluster';
        // PK and indexes
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addIndexInfo('cluster_idx', XMLDB_INDEX_NOTUNIQUE, array('clusterid'));
        $result = $result && create_table($table);
        $table = new XMLDBTable('crlm_usercluster');
        $f = new XMLDBField('autoenrol');
        $f->setAttributes(XMLDB_TYPE_INTEGER, '1', null, true, null, null, null, 1, 'clusterid');
        $f->comment = 'Whether users should be autoenrolled in tracks associated with this cluster.';
        $result = $result && add_field($table, $f);
    }
    if ($oldversion < 2009010109) {
        /// Define table crlm_class_moodle to be created
        $table = new XMLDBTable('crlm_class_moodle');
        /// Adding fields to table crlm_class_moodle
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('classid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('moodlecourseid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('enroltype', XMLDB_TYPE_INTEGER, '2', XMLDB_UNSIGNED, null, null, null, null, '0');
        $table->addFieldInfo('enrolplugin', XMLDB_TYPE_CHAR, '20', null, null, null, null, null, 'crlm');
        $table->addFieldInfo('timemodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        /// Adding keys to table crlm_class_moodle
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('mdl_currclasmood_clamoo_uix', XMLDB_KEY_UNIQUE, array('classid', 'moodlecourseid'));
        /// Launch create table for crlm_class_moodle
        $result = $result && create_table($table);
    }
    if ($oldversion < 2009010110) {
        $table = new XMLDBTable('crlm_user_track');
        $table->comment = 'User enrolment in tracks';
        // fields
        $f = $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', false, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $f = $table->addFieldInfo('userid', XMLDB_TYPE_INTEGER, '10', null, true, null, null, null, null, 'id');
        $f->comment = 'Foreign key to user id';
        $f = $table->addFieldInfo('trackid', XMLDB_TYPE_INTEGER, '10', null, true, null, null, null, null, 'userid');
        $f->comment = 'Foreign key to track id';
        // PK and indexes
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $result = $result && create_table($table);
    }
    if ($result && $oldversion < 2009010112) {
        /// Define table crlm_notification_log to be created
        $table = new XMLDBTable('crlm_notification_log');
        /// Adding fields to table crlm_notification_log
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('event', XMLDB_TYPE_CHAR, '166', null, null, null, null, null, null);
        $table->addFieldInfo('instance', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('userid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('data', XMLDB_TYPE_CHAR, '255', null, null, null, null, null, null);
        $table->addFieldInfo('timecreated', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        /// Adding keys to table crlm_notification_log
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        /// Adding indexes to table crlm_notification_log
        $table->addIndexInfo('event_inst_user_ix', XMLDB_INDEX_NOTUNIQUE, array('event', 'instance', 'userid'));
        /// Launch create table for crlm_notification_log
        $result = $result && create_table($table);
    }
    if ($result && $oldversion < 2009010113) {
        /// Define index event_inst_user_ix (not unique) to be dropped from crlm_notification_log
        $table = new XMLDBTable('crlm_notification_log');
        $index = new XMLDBIndex('event_inst_user_ix');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('event', 'instance', 'userid'));
        /// Launch drop index event_inst_user_ix
        $result = $result && drop_index($table, $index);
        /// Define index event_inst_user_ix (not unique) to be added to crlm_notification_log
        $table = new XMLDBTable('crlm_notification_log');
        $index = new XMLDBIndex('event_inst_user_ix');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('userid', 'instance', 'event'));
        /// Launch add index event_inst_user_ix
        $result = $result && add_index($table, $index);
    }
    if ($result && $oldversion < 2009010114) {
        // Creating track table
        $table = new XMLDBTable('crlm_track');
        $table->comment = 'Track table';
        // fields
        $f = $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', false, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $f = $table->addFieldInfo('curid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $f = $table->addFieldInfo('idnumber', XMLDB_TYPE_CHAR, '100', null, XMLDB_NOTNULL, null, null, null);
        $f = $table->addFieldInfo('name', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null);
        $f = $table->addFieldInfo('description', XMLDB_TYPE_TEXT, 'small', null, XMLDB_NOTNULL, null, null, null, null);
        $f = $table->addFieldInfo('startdate', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $f = $table->addFieldInfo('enddate', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $f = $table->addFieldInfo('timecreated', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $f = $table->addFieldInfo('timemodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        // PK and indexes
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addIndexInfo('track_curr_idx', XMLDB_INDEX_NOTUNIQUE, array('curid'));
        $result = $result && create_table($table);
        $table = new XMLDBTable('crlm_track_class');
        $table->comment = 'Track class table';
        $f = $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', false, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $f = $table->addFieldInfo('trackid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $f = $table->addFieldInfo('classid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $f = $table->addFieldInfo('courseid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $f = $table->addFieldInfo('requried', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $f = $table->addFieldInfo('autoenrol', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $f = $table->addFieldInfo('default', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $f = $table->addFieldInfo('timecreated', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $f = $table->addFieldInfo('timemodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addIndexInfo('trackid_idx', XMLDB_INDEX_NOTUNIQUE, array('trackid'));
        $table->addIndexInfo('track_classid_idx', XMLDB_INDEX_NOTUNIQUE, array('classid'));
        $table->addIndexInfo('track_courseid_idx', XMLDB_INDEX_NOTUNIQUE, array('courseid'));
        $result = $result && create_table($table);
    }
    if ($result && $oldversion < 2009010115) {
        /// Define table crlm_cluster_profile to be created
        $table = new XMLDBTable('crlm_cluster_profile');
        /// Adding fields to table crlm_cluster_profile
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('clusterid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('fieldid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('value', XMLDB_TYPE_TEXT, 'big', null, XMLDB_NOTNULL, null, null, null, null);
        /// Adding keys to table crlm_cluster_profile
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        /// Launch create table for crlm_cluster_profile
        $result = $result && create_table($table);
        /// Define table crlm_cluster_assignments to be created
        $table = new XMLDBTable('crlm_cluster_assignments');
        /// Adding fields to table crlm_cluster_assignments
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('clusterid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('userid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('plugin', XMLDB_TYPE_CHAR, '32', null, XMLDB_NOTNULL, null, null, null, null);
        /// Adding keys to table crlm_cluster_assignments
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        /// Launch create table for crlm_cluster_assignments
        $result = $result && create_table($table);
    }
    if ($result && $oldversion < 2009010116) {
        $table = new XMLDBTable('crlm_track_class');
        $field = new XMLDBField('default');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, '0', 'autoenrol');
        $result = $result && drop_field($table, $field);
        $field = new XMLDBField('defaulttrack');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, '0', 'autoenrol');
        $result = $result && add_field($table, $field);
    }
    if ($result && $oldversion < 2009010117) {
        /// Remove obsolete job code tables if they exist.
        $table = new XMLDBTable('crlm_jobcode_list');
        if (table_exists($table)) {
            drop_table($table);
        }
        $table = new XMLDBTable('crlm_curriculum_jobcode');
        if (table_exists($table)) {
            drop_table($table);
        }
    }
    if ($result && $oldversion < 2009010118) {
        /// Removing defaulttrack column from table
        $table = new XMLDBTable('crlm_track_class');
        $field = new XMLDBField('defaulttrack');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, '0', 'autoenrol');
        $result = $result && drop_field($table, $field);
        /// Adding defaulttrack column to table
        $table = new XMLDBTable('crlm_track');
        $field = new XMLDBField('defaulttrack');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, '0', 'enddate');
        $result = $result && add_field($table, $field);
    }
    if ($result && $oldversion < 2009010119) {
        /// Define field completed to be added to crlm_curriculum_assignment
        $table = new XMLDBTable('crlm_curriculum_assignment');
        $field = new XMLDBField('completed');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '2', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'curriculumid');
        /// Launch add field completed
        $result = $result && add_field($table, $field);
        /// Define field completiontime to be added to crlm_curriculum_assignment
        $field = new XMLDBField('timecompleted');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'completed');
        /// Launch add field completiontime
        $result = $result && add_field($table, $field);
        /// Define field credits to be added to crlm_curriculum_assignment
        $field = new XMLDBField('credits');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'timecompleted');
        /// Launch add field credits
        $result = $result && add_field($table, $field);
        /// Define field locked to be added to crlm_curriculum_assignment
        $table = new XMLDBTable('crlm_curriculum_assignment');
        $field = new XMLDBField('locked');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '2', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'credits');
        /// Launch add field locked
        $result = $result && add_field($table, $field);
        /// Define key mdl_currcurrassi_usecur_uix (unique) to be dropped from crlm_curriculum_assignment
        $key = new XMLDBKey('mdl_currcurrassi_usecur_uix');
        $key->setAttributes(XMLDB_KEY_UNIQUE, array('userid', 'curriculumid'));
        /// Launch drop key mdl_currcurrassi_usecur_uix
        $result = $result && drop_key($table, $key);
        /// Define index mdl_currcurrassi_usecurcom_ix (not unique) to be added to crlm_curriculum_assignment
        $index = new XMLDBIndex('mdl_currcurrassi_usecurcom_ix');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('userid', 'curriculumid', 'completed'));
        /// Launch add index mdl_currcurrassi_usecurcom_ix
        $result = $result && add_index($table, $index);
        /// Define index completed_ix (not unique) to be added to crlm_curriculum_assignment
        $index = new XMLDBIndex('completed_ix');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('completed'));
        /// Launch add index completed_ix
        $result = $result && add_index($table, $index);
    }
    if ($result && $oldversion < 2009010120) {
        /// Define field autoenrol to be added to crlm_cluster_assignments
        $table = new XMLDBTable('crlm_cluster_assignments');
        $field = new XMLDBField('autoenrol');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '1', 'plugin');
        /// Launch add field autoenrol
        $result = $result && add_field($table, $field);
    }
    if ($result && $oldversion < 2009010121) {
        if (!record_exists('mnet_application', 'name', 'java')) {
            $application = new stdClass();
            $application->name = 'java';
            $application->display_name = 'Java servlet';
            $application->xmlrpc_server_url = '/mnet/server';
            $application->sso_land_url = '/mnet/land.jsp';
            $result = $result && insert_record('mnet_application', $application, false);
        }
    }
    if ($result && $oldversion < 2009010122) {
        $table = new XMLDBTable('crlm_track_class');
        $field = new XMLDBField('requried');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'courseid');
        $result = $result && drop_field($table, $field);
    }
    if ($result && $oldversion < 2009010125) {
        $result = $result && execute_sql('CREATE OR REPLACE VIEW `courseNforums` AS select `f`.`id` AS `forumid`,concat(`c`.`shortname`,_utf8\' | \',`f`.`name`) AS `courseNforumname` from (`mdl_forum` `f` join `mdl_course` `c` on((`c`.`id` = `f`.`course`))) order by `c`.`shortname`,`f`.`name`');
    }
    if ($result && $oldversion < 2009010126) {
        $table = new XMLDBTable('crlm_cluster_curriculum');
        $table->comment = 'Association between clusters and curricula';
        // fields
        $f = $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', false, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $f = $table->addFieldInfo('clusterid', XMLDB_TYPE_INTEGER, '10', null, true, null, null, null, null, 'id');
        $f->comment = 'Foreign key to cluster id';
        $f = $table->addFieldInfo('curriculumid', XMLDB_TYPE_INTEGER, '10', null, true, null, null, null, null, 'clusterid');
        $f->comment = 'Foreign key to curriculum id';
        // PK and indexes
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addIndexInfo('cluster_idx', XMLDB_INDEX_NOTUNIQUE, array('clusterid'));
        $result = $result && (table_exists($table) || create_table($table));
        $table = new XMLDBTable('crlm_cluster_track');
        $table->comment = 'Association between clusters and tracks';
        // fields
        $f = $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', false, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $f = $table->addFieldInfo('clusterid', XMLDB_TYPE_INTEGER, '10', null, true, null, null, null, null, 'id');
        $f->comment = 'Foreign key to cluster id';
        $f = $table->addFieldInfo('trackid', XMLDB_TYPE_INTEGER, '10', null, true, null, null, null, null, 'clusterid');
        $f->comment = 'Foreign key to track id';
        $f = $table->addFieldInfo('autounenrol', XMLDB_TYPE_INTEGER, '1', null, true, null, null, null, null, 'trackid');
        $f->comment = 'Whether or not to remove a user from classes when removed from cluster';
        // PK and indexes
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addIndexInfo('cluster_idx', XMLDB_INDEX_NOTUNIQUE, array('clusterid'));
        $result = $result && (table_exists($table) || create_table($table));
    }
    if ($result && $oldversion < 2009010127) {
        // fix silly typos
        $newtable = new XMLDBTable('crlm_user_track');
        $oldtable = new XMLDBTable('clrm_user_track');
        $result = $result && (table_exists($newtable) || rename_table($oldtable, 'crlm_user_track'));
        $oldtable = new XMLDBTable('clrm_cluster_track');
        $result = $result && (!table_exists($oldtable) || drop_table($oldtable));
        $oldtable = new XMLDBTable('clrm_cluster_curriculum');
        $result = $result && (!table_exists($oldtable) || drop_table($oldtable));
    }
    if ($result && $oldversion < 2009010128) {
        require_once $CFG->dirroot . '/curriculum/lib/lib.php';
        cm_migrate_moodle_users();
    }
    if ($result && $oldversion < 2009010131) {
        /// Get rid of any outdated cluster data we might have lying around.
        if ($CFG->dbfamily == 'postgres') {
            $sql = "DELETE FROM {$CFG->prefix}crlm_cluster_assignments\n                    WHERE id IN (\n                        SELECT ca.clusterid\n                        FROM {$CFG->prefix}crlm_cluster_assignments ca\n                        LEFT JOIN {$CFG->prefix}crlm_cluster c ON c.id = ca.clusterid\n                        WHERE c.id IS NULL\n                    )";
            $result = $result && execute_sql($sql);
            $sql = "DELETE FROM {$CFG->prefix}crlm_cluster_curriculum\n                    WHERE id IN (\n                        SELECT cc.clusterid\n                        FROM {$CFG->prefix}crlm_cluster_curriculum cc\n                        LEFT JOIN {$CFG->prefix}crlm_cluster c ON c.id = cc.clusterid\n                        WHERE c.id IS NULL\n                    )";
            $result = $result && execute_sql($sql);
            $sql = "DELETE FROM {$CFG->prefix}crlm_cluster_profile\n                    WHERE id IN (\n                        SELECT cp.clusterid\n                        FROM {$CFG->prefix}crlm_cluster_profile cp\n                        LEFT JOIN {$CFG->prefix}crlm_cluster c ON c.id = cp.clusterid\n                        WHERE c.id IS NULL\n                    )";
            $result = $result && execute_sql($sql);
            $sql = "DELETE FROM {$CFG->prefix}crlm_cluster_track\n                    WHERE id IN (\n                        SELECT ct.clusterid\n                        FROM {$CFG->prefix}crlm_cluster_track ct\n                        LEFT JOIN {$CFG->prefix}crlm_cluster c ON c.id = ct.clusterid\n                        WHERE c.id IS NULL\n                    )";
            $result = $result && execute_sql($sql);
            $sql = "DELETE FROM {$CFG->prefix}crlm_usercluster\n                    WHERE id IN (\n                        SELECT uc.clusterid\n                        FROM {$CFG->prefix}crlm_usercluster uc\n                        LEFT JOIN {$CFG->prefix}crlm_cluster c ON c.id = uc.clusterid\n                        WHERE c.id IS NULL\n                    )";
            $result = $result && execute_sql($sql);
        } else {
            $sql = "DELETE ca FROM {$CFG->prefix}crlm_cluster_assignments ca\n                    LEFT JOIN {$CFG->prefix}crlm_cluster c ON c.id = ca.clusterid\n                    WHERE c.id IS NULL";
            $result = $result && execute_sql($sql);
            $sql = "DELETE cc FROM {$CFG->prefix}crlm_cluster_curriculum cc\n                    LEFT JOIN {$CFG->prefix}crlm_cluster c ON c.id = cc.clusterid\n                    WHERE c.id IS NULL";
            $result = $result && execute_sql($sql);
            $sql = "DELETE cp FROM {$CFG->prefix}crlm_cluster_profile cp\n                    LEFT JOIN {$CFG->prefix}crlm_cluster c ON c.id = cp.clusterid\n                    WHERE c.id IS NULL";
            $result = $result && execute_sql($sql);
            $sql = "DELETE ct FROM {$CFG->prefix}crlm_cluster_track ct\n                    LEFT JOIN {$CFG->prefix}crlm_cluster c ON c.id = ct.clusterid\n                    WHERE c.id IS NULL";
            $result = $result && execute_sql($sql);
            $sql = "DELETE uc FROM {$CFG->prefix}crlm_usercluster uc\n                    LEFT JOIN {$CFG->prefix}crlm_cluster c ON c.id = uc.clusterid\n                    WHERE c.id IS NULL";
            $result = $result && execute_sql($sql);
        }
    }
    if ($result && $oldversion < 2009010133) {
        /// Define field leader to be added to crlm_cluster_assignments
        $table = new XMLDBTable('crlm_cluster_assignments');
        $field = new XMLDBField('leader');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'autoenrol');
        /// Launch add field leader
        $result = $result && add_field($table, $field);
        /// Define field leader to be added to crlm_usercluster
        $table = new XMLDBTable('crlm_usercluster');
        $field = new XMLDBField('leader');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'autoenrol');
        /// Launch add field leader
        $result = $result && add_field($table, $field);
    }
    if ($result && $oldversion < 2009010134) {
        /// Define field inactive to be added to crlm_user
        $table = new XMLDBTable('crlm_user');
        $field = new XMLDBField('inactive');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, null, null, null, null, '0', 'timemodified');
        /// Launch add field inactive
        $result = $result && add_field($table, $field);
    }
    if ($result && $oldversion < 2009010137) {
        $roleid = get_field('role', 'id', 'shortname', 'curriculumadmin');
        if (!empty($roleid)) {
            $context = get_context_instance(CONTEXT_SYSTEM, SITEID);
            require_once dirname(dirname(__FILE__)) . '/db/access.php';
            if (!empty($block_curr_admin_capabilities)) {
                foreach ($block_curr_admin_capabilities as $capname => $caprules) {
                    $result = $result && assign_capability($capname, CAP_ALLOW, $roleid, $context->id);
                }
            }
        }
    }
    if ($result && $oldversion < 2009010139) {
        global $CURMAN;
        require_once $CFG->dirroot . '/curriculum/lib/classmoodlecourse.class.php';
        $moodleclasses = moodle_get_classes();
        if (!empty($moodleclasses)) {
            foreach ($moodleclasses as $class) {
                $context = get_context_instance(CONTEXT_COURSE, $class->moodlecourseid);
                $sql = "DELETE cmce\n                    FROM {$CURMAN->db->prefix_table('user')} u\n                    JOIN {$CURMAN->db->prefix_table('role_assignments')} ra ON u.id = ra.userid\n                    JOIN {$CURMAN->db->prefix_table(STUTABLE)} cmce ON u.idnumber = cmce.user_idnumber\n                    WHERE ra.roleid NOT IN ({$CFG->gradebookroles})\n                    AND ra.contextid " . get_related_contexts_string($context) . "AND cmce.classid = {$class->classid}";
                $result = $result && execute_sql($sql);
            }
        }
    }
    if ($result && $oldversion < 2009010140) {
        delete_records('crlm_cluster_profile', 'fieldid', 0);
    }
    if ($result && $oldversion < 2009010141) {
        set_config('field_lock_idnumber', 'locked', 'auth/manual');
    }
    if ($result && $oldversion < 2009010143) {
        /// Define table crlm_wait_list to be created
        $table = new XMLDBTable('crlm_wait_list');
        /// Adding fields to table crlm_wait_list
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('classid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('userid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('timecreated', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('timemodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('position', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        /// Adding keys to table crlm_wait_list
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        /// Launch create table for crlm_wait_list
        $result = $result && create_table($table);
    }
    if ($result && $oldversion < 2009010145) {
        $table = new XMLDBTable('crlm_wait_list');
        $field = new XMLDBField('enrolmenttime');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $result = $result && add_field($table, $field);
    }
    if ($result && $oldversion < 2009010146) {
        // make sure trackclass's courseids are set
        // Let's just assume that all non-Postgres DB's use the same syntax as MySQL and call it a day.
        if ($CFG->dbfamily == 'postgres') {
            $sql = "UPDATE {$CFG->prefix}crlm_track_class\n                       SET courseid = c.courseid\n                      FROM {$CFG->prefix}crlm_track_class tc, {$CFG->prefix}crlm_class c\n                     WHERE tc.classid = c.id AND tc.courseid = 0";
        } else {
            $sql = "UPDATE {$CFG->prefix}crlm_track_class tc, {$CFG->prefix}crlm_class c\n                       SET tc.courseid = c.courseid\n                     WHERE tc.classid = c.id AND tc.courseid = 0";
        }
        $result = $result && execute_sql($sql);
    }
    if ($result && $oldversion < 2009010147) {
        // make sure all users have an idnumber
        $users = get_records('crlm_user', 'idnumber', '');
        foreach ($users as $user) {
            $user = addslashes_recursive($user);
            $mu = addslashes_recursive(get_record('user', 'username', $user->username));
            if (empty($mu->idnumber)) {
                $user->idnumber = $mu->idnumber = $mu->username;
                update_record('user', $mu);
                update_record('crlm_user', $user);
            } else {
                if (!get_record('crlm_user', 'idnumber', $mu->idnumber)) {
                    $user->idnumber = $mu->idnumber;
                    update_record('crlm_user', $user);
                } else {
                    if (!get_record('crlm_user', 'idnumber', $user->username)) {
                        $user->idnumber = $mu->idnumber;
                        update_record('crlm_user', $user);
                    }
                }
            }
        }
    }
    if ($result && $oldversion < 2009010149) {
        /// Define index clusterid_idx (not unique) to be added to crlm_cluster_assignments
        $table = new XMLDBTable('crlm_cluster_assignments');
        $index = new XMLDBIndex('clusterid_idx');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('clusterid'));
        /// Launch add index clusterid_idx
        $result = $result && add_index($table, $index);
        /// Define index userid_idx (not unique) to be added to crlm_cluster_assignments
        $table = new XMLDBTable('crlm_cluster_assignments');
        $index = new XMLDBIndex('userid_idx');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('userid'));
        /// Launch add index userid_idx
        $result = $result && add_index($table, $index);
        /// Define index clusterid_idx (not unique) to be added to crlm_cluster_profile
        $table = new XMLDBTable('crlm_cluster_profile');
        $index = new XMLDBIndex('clusterid_idx');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('clusterid'));
        /// Launch add index clusterid_idx
        $result = $result && add_index($table, $index);
    }
    if ($result && $oldversion < 2009010151) {
        $table = new XMLDBTable('crlm_curriculum');
        $field = new XMLDBField('priority');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $result = $result && add_field($table, $field);
    }
    if ($result && $oldversion < 2009010150) {
        require_once CURMAN_DIRLOCATION . '/lib/curriculumcourse.class.php';
        $sql = "SELECT cp.id, cp.courseid, cc.curriculumid\n                FROM {$CFG->prefix}crlm_course_prerequisite cp\n                JOIN {$CFG->prefix}crlm_curriculum_course cc ON cc.id = cp.curriculumcourseid\n                WHERE cp.courseid NOT IN (\n                    SELECT _cc.courseid\n                    FROM {$CFG->prefix}crlm_curriculum_course _cc\n                    WHERE _cc.curriculumid = cc.curriculumid\n                )";
        $students = get_records_sql($sql);
        $retval = 0;
        foreach ($students as $student) {
            $data = new object();
            $data->curriculumid = $student->curriculumid;
            $data->courseid = $student->courseid;
            $data->timeperiod = 'year';
            $currprereq = new curriculumcourse($data);
            $retval = $result && $currprereq->add();
        }
        $results = $retval;
    }
    if ($result && $oldversion < 2009103001) {
        $table = new XMLDBTable('crlm_curriculum');
        $field = new XMLDBField('priority');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $result = $result && add_field($table, $field);
        /// Define table context_levels to be created
        $table = new XMLDBTable('context_levels');
        /// Adding fields to table context_levels
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('name', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('component', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        /// Adding keys to table context_levels
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        /// Adding indexes to table context_levels
        $table->addIndexInfo('name', XMLDB_INDEX_NOTUNIQUE, array('name'));
        $table->addIndexInfo('component', XMLDB_INDEX_NOTUNIQUE, array('component'));
        /// Launch create table for context_levels
        $result = $result && create_table($table);
    }
    if ($result && $oldversion < 2009103003) {
        /// Define table crlm_field to be created
        $table = new XMLDBTable('crlm_field');
        /// Adding fields to table crlm_field
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('shortname', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('name', XMLDB_TYPE_TEXT, 'big', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('datatype', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('description', XMLDB_TYPE_TEXT, 'big', null, null, null, null, null, null);
        $table->addFieldInfo('categoryid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('sortorder', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('required', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('locked', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('visible', XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('forceunique', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('defaultdata', XMLDB_TYPE_TEXT, 'big', null, null, null, null, null, null);
        $table->addFieldInfo('params', XMLDB_TYPE_TEXT, 'big', null, null, null, null, null, null);
        $table->addFieldInfo('syncwithmoodle', XMLDB_TYPE_INTEGER, '2', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        /// Adding keys to table crlm_field
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        /// Adding indexes to table crlm_field
        $table->addIndexInfo('shortname_idx', XMLDB_INDEX_NOTUNIQUE, array('shortname'));
        /// Launch create table for crlm_field
        $result = $result && create_table($table);
        /// Define table crlm_field_category to be created
        $table = new XMLDBTable('crlm_field_category');
        /// Adding fields to table crlm_field_category
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('name', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('sortorder', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        /// Adding keys to table crlm_field_category
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        /// Launch create table for crlm_field_category
        $result = $result && create_table($table);
        /// Define table crlm_field_contextlevel to be created
        $table = new XMLDBTable('crlm_field_contextlevel');
        /// Adding fields to table crlm_field_contextlevel
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('fieldid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('contextlevel', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        /// Adding keys to table crlm_field_contextlevel
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        /// Launch create table for crlm_field_contextlevel
        $result = $result && create_table($table);
        /// Define table crlm_field_data to be created
        $table = new XMLDBTable('crlm_field_data');
        /// Adding fields to table crlm_field_data
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('contextid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('fieldid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('data', XMLDB_TYPE_TEXT, 'big', null, XMLDB_NOTNULL, null, null, null, null);
        /// Adding keys to table crlm_field_data
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        /// Adding indexes to table crlm_field_data
        $table->addIndexInfo('context_idx', XMLDB_INDEX_NOTUNIQUE, array('contextid'));
        /// Launch create table for crlm_field_data
        $result = $result && create_table($table);
    }
    //if ($result && $oldversion < 2010040501) {
    //    require_once($CFG->dirroot . '/blocks/curr_admin/lib.php');
    //    $result = $result && create_views(); // create with default prefix
    //    $result = $result && create_views(''); // create with no prefix
    //}
    if ($result && $oldversion < 2010040501) {
        $table = new XMLDBTable('crlm_field_map');
        /// Adding fields to table crlm_field_data
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('context', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('type', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('elis_field', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('data_field', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        /// Adding keys to table crlm_field_data
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        /// Launch create table for crlm_field_data
        $result = $result && create_table($table);
    }
    if ($result && $oldversion < 2010040501) {
        require_once "{$CFG->dirroot}/curriculum/lib/customfield.class.php";
        // make sure all ELIS users have a context
        update_capabilities('block/curr_admin');
        $ctxlvl = context_level_base::get_custom_context_level('user', 'block_curr_admin');
        $rs = get_recordset('crlm_user');
        while ($rec = rs_fetch_next_record($rs)) {
            get_context_instance($ctxlvl, $rec->id);
        }
        // sync profile fields
        $fields = field::get_for_context_level($ctxlvl);
        $fields = $fields ? $fields : array();
        require_once $CFG->dirroot . '/curriculum/plugins/moodle_profile/custom_fields.php';
        foreach ($fields as $field) {
            $fieldobj = new field($field);
            $sync_profile_field_with_moodle();
        }
    }
    if ($result && $oldversion < 2010040501) {
        require_once $CFG->dirroot . '/curriculum/lib/notifications.php';
        if (!empty($CFG->coursemanager)) {
            $context_course = CONTEXT_COURSE;
            $sql = "SELECT role_assignments.* FROM {$CFG->prefix}role_assignments role_assignments\n                    JOIN {$CFG->prefix}context context\n                    ON role_assignments.contextid = context.id\n                    WHERE role_assignments.roleid IN ({$CFG->coursemanager})\n                    AND context.contextlevel = {$context_course}";
            if ($records = get_records_sql($sql)) {
                foreach ($records as $record) {
                    cm_assign_instructor_from_mdl($record);
                }
            }
        }
    }
    if ($result && $oldversion < 2010063001) {
        $table = new XMLDBTable('crlm_curriculum_assignment');
        $field = new XMLDBField('user_idnumber');
        $result = $result && drop_field($table, $field);
        $table = new XMLDBTable('crlm_class_enrolment');
        $field = new XMLDBField('user_idnumber');
        $result = $result && drop_field($table, $field);
        $table = new XMLDBTable('crlm_class_instructor');
        $field = new XMLDBField('user_idnumber');
        $result = $result && drop_field($table, $field);
        $table = new XMLDBTable('crlm_class_attendance');
        $field = new XMLDBField('user_idnumber');
        $result = $result && drop_field($table, $field);
    }
    //if ($result && $oldversion < 2010063002) {
    //    require_once($CFG->dirroot . '/blocks/curr_admin/lib.php');
    //    $result = $result && create_views(); // create with default prefix
    //    $result = $result && create_views(''); // create with no prefix
    //}
    if ($result && $oldversion < 2010040505) {
        require_once $CFG->dirroot . '/curriculum/lib/lib.php';
        $result = $result && cm_notify_duplicate_user_info(true);
    }
    if ($result && $oldversion < 2010040506 && $oldversion >= 2010040501) {
        global $CFG, $CURMAN;
        // fix instructor assignments that were migrated incorrectly in the
        // 2010040501 upgrade code (ELIS-1171)
        // remove the obvious errors (instructors assigned to a non-existent class)
        $context_course = CONTEXT_COURSE;
        $sql = "DELETE\n                  FROM {$CFG->prefix}crlm_class_instructor\n                 WHERE NOT EXISTS (SELECT 'x' FROM {$CFG->prefix}crlm_class cmclass\n                                    WHERE cmclass.id = {$CFG->prefix}crlm_class_instructor.classid)";
        $result = $result && execute_sql($sql);
        // warn about other potentially incorrect instructor assignments
        require_once $CFG->dirroot . '/curriculum/lib/lib.php';
        cm_notify_incorrect_instructor_assignment(true);
        // make sure the correct assignments are added
        if (!empty($CFG->coursemanager)) {
            require_once $CFG->dirroot . '/curriculum/lib/notifications.php';
            $context_course = CONTEXT_COURSE;
            $sql = "SELECT role_assignments.* FROM {$CFG->prefix}role_assignments role_assignments\n                    JOIN {$CFG->prefix}context context\n                    ON role_assignments.contextid = context.id\n                    WHERE role_assignments.roleid IN ({$CFG->coursemanager})\n                    AND context.contextlevel = {$context_course}";
            if ($records = get_records_sql($sql)) {
                foreach ($records as $record) {
                    cm_assign_instructor_from_mdl($record);
                }
            }
        }
    }
    if ($result && $oldversion < 2010063002) {
        //get the class table
        $table = new XMLDBTable('crlm_class');
        //add the auto enrol enabled flag
        $field = new XMLDBField('enrol_from_waitlist');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, '0');
        $result = $result && add_field($table, $field);
    }
    if ($result && $oldversion < 2010063005) {
        /// Define table crlm_field_data to be dropped
        $table = new XMLDBTable('crlm_field_map');
        /// Launch drop table for crlm_field_data
        $result = $result && drop_table($table);
    }
    if ($result && $oldversion < 2010063006) {
        /// Define table crlm_field_data to be renamed to crlm_field_data_text
        $table = new XMLDBTable('crlm_field_data');
        /// Define index context_idx (not unique) to be dropped form crlm_field_data_text
        $index = new XMLDBIndex('context_idx');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('contextid'));
        /// Launch drop index context_idx
        $result = $result && drop_index($table, $index);
        /// Changing nullability of field contextid on table crlm_field_data_text to null
        $field = new XMLDBField('contextid');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null, 'id');
        /// Define index context_idx (not unique) to be added to crlm_field_data_text
        $index = new XMLDBIndex('context_idx');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('contextid'));
        /// Launch add index context_idx
        $result = $result && add_index($table, $index);
        /// Define index field_idx (not unique) to be added to crlm_field_data_text
        $index = new XMLDBIndex('field_idx');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('fieldid'));
        /// Launch add index field_idx
        $result = $result && add_index($table, $index);
        /// Launch change of nullability for field contextid
        $result = $result && change_field_notnull($table, $field);
        /// Launch rename table for crlm_field_data
        $result = $result && rename_table($table, 'crlm_field_data_text');
        /// Define table crlm_field_owner to be created
        $table = new XMLDBTable('crlm_field_owner');
        /// Adding fields to table crlm_field_owner
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('fieldid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('plugin', XMLDB_TYPE_CHAR, '255', null, null, null, null, null, null);
        $table->addFieldInfo('exclude', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, null, null, null, null, '0');
        $table->addFieldInfo('params', XMLDB_TYPE_TEXT, 'big', null, null, null, null, null, null);
        /// Adding keys to table crlm_field_owner
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        /// Adding indexes to table crlm_field_owner
        $table->addIndexInfo('field_idx', XMLDB_INDEX_NOTUNIQUE, array('fieldid'));
        /// Launch create table for crlm_field_owner
        $result = $result && create_table($table);
        /// Define table crlm_field_category_context to be created
        $table = new XMLDBTable('crlm_field_category_context');
        /// Adding fields to table crlm_field_category_context
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('categoryid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('contextlevel', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        /// Adding keys to table crlm_field_category_context
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        /// Adding indexes to table crlm_field_category_context
        $table->addIndexInfo('contextlevel_idx', XMLDB_INDEX_NOTUNIQUE, array('contextlevel'));
        $table->addIndexInfo('category_idx', XMLDB_INDEX_NOTUNIQUE, array('categoryid'));
        /// Launch create table for crlm_field_category_context
        $result = $result && create_table($table);
        $usercontextid = context_level_base::get_custom_context_level('user', 'block_curr_admin');
        if ($usercontextid) {
            $sql = "INSERT INTO {$CFG->prefix}crlm_field_category_context\n                           (categoryid, contextlevel)\n                    SELECT id, {$usercontextid}\n                      FROM {$CFG->prefix}crlm_field_category";
            $result = $result && execute_sql($sql);
        }
        /// Define table crlm_field_data_int to be created
        $table = new XMLDBTable('crlm_field_data_int');
        /// Adding fields to table crlm_field_data_int
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('contextid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('fieldid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('data', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, null);
        /// Adding keys to table crlm_field_data_int
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        /// Adding indexes to table crlm_field_data_int
        $table->addIndexInfo('context_idx', XMLDB_INDEX_NOTUNIQUE, array('contextid'));
        $table->addIndexInfo('field_idx', XMLDB_INDEX_NOTUNIQUE, array('fieldid'));
        /// Launch create table for crlm_field_data_int
        $result = $result && create_table($table);
        /// Define table crlm_field_data_num to be created
        $table = new XMLDBTable('crlm_field_data_num');
        /// Adding fields to table crlm_field_data_num
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('contextid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('fieldid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('data', XMLDB_TYPE_NUMBER, '15, 5', null, XMLDB_NOTNULL, null, null, null, null);
        /// Adding keys to table crlm_field_data_num
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        /// Adding indexes to table crlm_field_data_num
        $table->addIndexInfo('context_idx', XMLDB_INDEX_NOTUNIQUE, array('contextid'));
        $table->addIndexInfo('field_idx', XMLDB_INDEX_NOTUNIQUE, array('fieldid'));
        /// Launch create table for crlm_field_data_num
        $result = $result && create_table($table);
        /// Define table crlm_field_data_char to be created
        $table = new XMLDBTable('crlm_field_data_char');
        /// Adding fields to table crlm_field_data_char
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('contextid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('fieldid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('data', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        /// Adding keys to table crlm_field_data_char
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        /// Adding indexes to table crlm_field_data_char
        $table->addIndexInfo('context_idx', XMLDB_INDEX_NOTUNIQUE, array('contextid'));
        $table->addIndexInfo('field_idx', XMLDB_INDEX_NOTUNIQUE, array('fieldid'));
        /// Launch create table for crlm_field_data_char
        $result = $result && create_table($table);
        $records = get_records('crlm_field');
        if ($records) {
            // FIXME: set data type based on old data type
            foreach ($records as $record) {
                unset($record->name);
                unset($record->shortname);
                unset($record->description);
                $record->defaultdata = addslashes($record->defaultdata);
                if (isset($record->syncwithmoodle)) {
                    // make sure the crlm_field table hasn't been upgraded yet
                    switch ($record->syncwithmoodle) {
                        case 2:
                            // sync from Moodle
                            // create "moodle_profile" owner
                            if (!record_exists('crlm_field_owner', 'fieldid', $record->id, 'plugin', 'moodle_profile')) {
                                $owner = new stdClass();
                                $owner->fieldid = $record->id;
                                $owner->plugin = 'moodle_profile';
                                $owner->exclude = true;
                                $result = $result && insert_record('crlm_field_owner', $owner);
                            }
                            // create "manual" owner
                            if (!record_exists('crlm_field_owner', 'fieldid', $record->id, 'plugin', 'manual')) {
                                $owner = new stdClass();
                                $owner->fieldid = $record->id;
                                $owner->plugin = 'manual';
                                $owner->exclude = false;
                                $owner->params = array('edit_capability' => 'disabled');
                                if (!$record->visible) {
                                    $owner->params['view_capability'] = 'moodle/user:viewhiddendetails';
                                }
                                $owner->params = serialize($owner->params);
                                $result = $result && insert_record('crlm_field_owner', $owner);
                            }
                            $record->datatype = 'text';
                            break;
                        case 1:
                            // sync to Moodle
                            // create "moodle_profile" owner
                            if (!record_exists('crlm_field_owner', 'fieldid', $record->id, 'plugin', 'moodle_profile')) {
                                $owner = new stdClass();
                                $owner->fieldid = $record->id;
                                $owner->plugin = 'moodle_profile';
                                $owner->exclude = false;
                                $result = $result && insert_record('crlm_field_owner', $owner);
                            }
                            // NOTE: fall through
                        // NOTE: fall through
                        default:
                            // no sync or invalid user
                            // create "manual" owner
                            $controltype = $record->datatype;
                            $record->datatype = 'text';
                            if (!record_exists('crlm_field_owner', 'fieldid', $record->id, 'plugin', 'manual')) {
                                $owner = new stdClass();
                                $owner->fieldid = $record->id;
                                $owner->plugin = 'manual';
                                $owner->exclude = false;
                                $owner->params = array('control' => $controltype, 'required' => $record->required);
                                if ($record->locked) {
                                    $owner->params['edit_capability'] = 'moodle/user:update';
                                }
                                if (!$record->visible) {
                                    $owner->params['view_capability'] = 'moodle/user:viewhiddendetails';
                                }
                                if (!empty($record->params)) {
                                    $owner->params += unserialize($record->params);
                                }
                                switch ($controltype) {
                                    case 'checkbox':
                                        // legacy checkboxes are all boolean
                                        $record->datatype = 'bool';
                                        $data_recs = get_records('crlm_field_data_text', 'fieldid', $record->id);
                                        foreach ($data_recs as $data_rec) {
                                            delete_records('crlm_field_data_text', 'id', $data_rec->id);
                                            unset($data_rec->id);
                                            insert_record('crlm_field_data_int', $data_rec);
                                        }
                                        break;
                                    case 'menu':
                                        // menu items should be short text
                                        $record->datatype = 'char';
                                        $data_recs = get_records('crlm_field_data_text', 'fieldid', $record->id);
                                        foreach ($data_recs as $data_rec) {
                                            delete_records('crlm_field_data_text', 'id', $data_rec->id);
                                            unset($data_rec->id);
                                            insert_record('crlm_field_data_char', $data_rec);
                                        }
                                    case 'text':
                                        $owner->params['columns'] = $owner->params['size'];
                                        unset($owner->params['size']);
                                        break;
                                }
                                $owner->params = addslashes(serialize($owner->params));
                                $result = $result && insert_record('crlm_field_owner', $owner);
                            }
                            break;
                    }
                    $record->params = '';
                    $result = $result && update_record('crlm_field', $record);
                    if (!empty($record->defaultdata)) {
                        if (!record_exists_select('crlm_field_data_text', "fieldid = {$record->id} AND contextid IS NULL")) {
                            $defaultdata = new stdClass();
                            $defaultdata->fieldid = $record->id;
                            $defaultdata->data = $record->defaultdata;
                            $result = $result && insert_record('crlm_field_data_text', $defaultdata);
                        }
                    }
                }
            }
        }
        $table = new XMLDBTable('crlm_field');
        /// Define field required to be dropped from crlm_field
        $field = new XMLDBField('required');
        /// Launch drop field required
        $result = $result && drop_field($table, $field);
        /// Define field locked to be dropped from crlm_field
        $field = new XMLDBField('locked');
        /// Launch drop field locked
        $result = $result && drop_field($table, $field);
        /// Define field visible to be dropped from crlm_field
        $field = new XMLDBField('visible');
        /// Launch drop field visible
        $result = $result && drop_field($table, $field);
        /// Define field defaultdata to be dropped from crlm_field
        $field = new XMLDBField('defaultdata');
        /// Launch drop field defaultdata
        $result = $result && drop_field($table, $field);
        /// Define field syncwithmoodle to be dropped from crlm_field
        $field = new XMLDBField('syncwithmoodle');
        /// Launch drop field syncwithmoodle
        $result = $result && drop_field($table, $field);
        /// Define field multivalued to be added to crlm_field
        $field = new XMLDBField('multivalued');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, null, null, null, null, '0', 'sortorder');
        /// Launch add field multivalued
        $result = $result && add_field($table, $field);
    }
    if ($result && $oldversion < 2010063007) {
        // install.xml accidentally had the char table use an integer data field
        /// Changing type of field data on table crlm_field_data_char to char
        $table = new XMLDBTable('crlm_field_data_char');
        $field = new XMLDBField('data');
        $field->setAttributes(XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null, 'fieldid');
        /// Launch change of type for field data
        $result = $result && change_field_type($table, $field);
    }
    if ($result && $oldversion < 2010063008) {
        $table = new XMLDBTable('crlm_cluster_curriculum');
        $field = new XMLDBField('autoenrol');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '1', 'curriculumid');
        $result = $result && add_field($table, $field);
        $table = new XMLDBTable('crlm_cluster_track');
        $field = new XMLDBField('autoenrol');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '1', 'trackid');
        $result = $result && add_field($table, $field);
        /// Define field parent to be added to crlm_cluster
        $table = new XMLDBTable('crlm_cluster');
        $field = new XMLDBField('parent');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'display');
        /// Launch add field parent
        $result = $result && add_field($table, $field);
        /// Define field depth to be added to crlm_cluster
        $field = new XMLDBField('depth');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '1', 'parent');
        /// Launch add field depth
        $result = $result && add_field($table, $field);
    }
    if ($result && $oldversion < 2010063013) {
        /*
         * Curriculum
         */
        $table = new XMLDBTable('crlm_curriculum');
        //name field
        $index = new XMLDBIndex('name_ix');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('name'));
        if (!index_exists($table, $index)) {
            $result = $result && add_index($table, $index);
        }
        /*
         * Course
         */
        $table = new XMLDBTable('crlm_course');
        //name field
        $index = new XMLDBIndex('name_ix');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('name'));
        if (!index_exists($table, $index)) {
            $result = $result && add_index($table, $index);
        }
        //credits field
        $index = new XMLDBIndex('credits_ix');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('credits'));
        if (!index_exists($table, $index)) {
            $result = $result && add_index($table, $index);
        }
        /*
         * Class
         */
        $table = new XMLDBTable('crlm_class');
        //idnumber field
        $index = new XMLDBIndex('idnumber_ix');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('idnumber'));
        if (!index_exists($table, $index)) {
            $result = $result && add_index($table, $index);
        }
        //enddate field
        $index = new XMLDBIndex('enddate_ix');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('enddate'));
        if (!index_exists($table, $index)) {
            $result = $result && add_index($table, $index);
        }
        /*
         * Class enrolment
         */
        $table = new XMLDBTable('crlm_class_enrolment');
        //completetime field
        $index = new XMLDBIndex('completetime_ix');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('completetime'));
        if (!index_exists($table, $index)) {
            $result = $result && add_index($table, $index);
        }
        //completestatusid field
        $index = new XMLDBIndex('completestatusid_ix');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('completestatusid'));
        if (!index_exists($table, $index)) {
            $result = $result && add_index($table, $index);
        }
        /*
         * CM user
         */
        $table = new XMLDBTable('crlm_user');
        //lastname field
        $index = new XMLDBIndex('lastname_ix');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('lastname'));
        if (!index_exists($table, $index)) {
            $result = $result && add_index($table, $index);
        }
        //firstname field
        $index = new XMLDBIndex('firstname_ix');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('firstname'));
        if (!index_exists($table, $index)) {
            $result = $result && add_index($table, $index);
        }
    }
    if ($result && $oldversion < 2010063015) {
        /// Define field autocreated to be added to crlm_class_moodle
        $table = new XMLDBTable('crlm_class_moodle');
        $field = new XMLDBField('autocreated');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '2', null, XMLDB_NOTNULL, null, null, null, '-1', 'timemodified');
        /// Launch add field autocreated
        $result = $result && add_field($table, $field);
    }
    if ($result && $oldversion < 2010111300) {
        $table = new XMLDBTable('crlm_curriculum_assignment');
        $field = new XMLDBField('timeexpired');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'timecompleted');
        // Launch add field multivalued
        $result = $result && add_field($table, $field);
    }
    if ($result && $oldversion < 2011050200) {
        /// Define index startdate_ix (not unique) to be added to crlm_class
        $table = new XMLDBTable('crlm_class');
        $index = new XMLDBIndex('startdate_ix');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('startdate'));
        $result = $result && add_index($table, $index);
        /// Define index enrolmenttime_ix (not unique) to be added to crlm_class_enrolment
        $table = new XMLDBTable('crlm_class_enrolment');
        $index = new XMLDBIndex('enrolmenttime_ix');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('enrolmenttime'));
        $result = $result && add_index($table, $index);
        /// Define index locked_ix (not unique) to be added to crlm_class_graded
        $table = new XMLDBTable('crlm_class_graded');
        $index = new XMLDBIndex('locked_ix');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('locked'));
        $result = $result && add_index($table, $index);
        /// Define index timegraded_ix (not unique) to be added to crlm_class_graded
        $table = new XMLDBTable('crlm_class_graded');
        $index = new XMLDBIndex('timegraded_ix');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('timegraded'));
        $result = $result && add_index($table, $index);
        /// Define index classid_ix (not unique) to be added to crlm_class_moodle
        $table = new XMLDBTable('crlm_class_moodle');
        $index = new XMLDBIndex('classid_ix');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('classid'));
        $result = $result && add_index($table, $index);
        /// Define index curriculumid_ix (not unique) to be added to crlm_cluster_curriculum
        $table = new XMLDBTable('crlm_cluster_curriculum');
        $index = new XMLDBIndex('curriculumid_ix');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('curriculumid'));
        $result = $result && add_index($table, $index);
        /// Define index fieldid_ix (not unique) to be added to crlm_cluster_profile
        $table = new XMLDBTable('crlm_cluster_profile');
        $index = new XMLDBIndex('fieldid_ix');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('fieldid'));
        $result = $result && add_index($table, $index);
        /// Define index trackid_ix (not unique) to be added to crlm_cluster_track
        $table = new XMLDBTable('crlm_cluster_track');
        $index = new XMLDBIndex('trackid_ix');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('trackid'));
        $result = $result && add_index($table, $index);
        /// Define index idnumber_ix (not unique) to be added to crlm_course_completion
        $table = new XMLDBTable('crlm_course_completion');
        $index = new XMLDBIndex('idnumber_ix');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('idnumber'));
        $result = $result && add_index($table, $index);
        /// Define index sortorder_ix (not unique) to be added to crlm_field
        $table = new XMLDBTable('crlm_field');
        $index = new XMLDBIndex('sortorder_ix');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('sortorder'));
        $result = $result && add_index($table, $index);
        /// Define index username_ix (not unique) to be added to crlm_user
        $table = new XMLDBTable('crlm_user');
        $index = new XMLDBIndex('username_ix');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('username'));
        $result = $result && add_index($table, $index);
        /// Define index inactive_ix (not unique) to be added to crlm_user
        $table = new XMLDBTable('crlm_user');
        $index = new XMLDBIndex('inactive_ix');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('inactive'));
        $result = $result && add_index($table, $index);
        /// Define index userid_ix (not unique) to be added to crlm_user_track
        $table = new XMLDBTable('crlm_user_track');
        $index = new XMLDBIndex('userid_ix');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('userid'));
        $result = $result && add_index($table, $index);
        /// Define index trackid_ix (not unique) to be added to crlm_user_track
        $table = new XMLDBTable('crlm_user_track');
        $index = new XMLDBIndex('trackid_ix');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('trackid'));
        $result = $result && add_index($table, $index);
        /// Define index classid_ix (not unique) to be added to crlm_wait_list
        $table = new XMLDBTable('crlm_wait_list');
        $index = new XMLDBIndex('classid_ix');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('classid'));
        $result = $result && add_index($table, $index);
        /// Define index userid_ix (not unique) to be added to crlm_wait_list
        $table = new XMLDBTable('crlm_wait_list');
        $index = new XMLDBIndex('userid_ix');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('userid'));
        $result = $result && add_index($table, $index);
    }
    if ($result && $oldversion < 2011050201) {
        // make sure that hours are within 24 hours
        $sql = "UPDATE {$CFG->prefix}crlm_class\n                   SET starttimehour = MOD(starttimehour, 24),\n                       endtimehour = MOD(endtimehour, 24)";
        $result = $result && execute_sql($sql);
    }
    if ($result && $oldversion < 2011050202) {
        /// Changing type of field credits on table crlm_class_enrolment to number
        $table = new XMLDBTable('crlm_class_enrolment');
        $field = new XMLDBField('credits');
        $field->setAttributes(XMLDB_TYPE_NUMBER, '10, 2', XMLDB_UNSIGNED, null, null, null, null, '0', 'grade');
        /// Launch change of type for field credits
        $result = $result && change_field_type($table, $field);
        /// Changing type of field credits on table crlm_curriculum_assignment to number
        $table = new XMLDBTable('crlm_curriculum_assignment');
        $field = new XMLDBField('credits');
        $field->setAttributes(XMLDB_TYPE_NUMBER, '10, 2', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'timeexpired');
        /// Launch change of type for field credits
        $result = $result && change_field_type($table, $field);
        /// Changing type of field reqcredits on table crlm_curriculum to number
        $table = new XMLDBTable('crlm_curriculum');
        $field = new XMLDBField('reqcredits');
        $field->setAttributes(XMLDB_TYPE_NUMBER, '10, 2', XMLDB_UNSIGNED, null, null, null, null, null, 'description');
        /// Launch change of type for field reqcredits
        $result = $result && change_field_type($table, $field);
        // update student class credits with decimal credits
        if ($CFG->dbfamily == 'postgres') {
            $sql = "UPDATE {$CFG->prefix}crlm_class_enrolment\n                       SET credits = CAST(c.credits AS numeric)\n                      FROM {$CFG->prefix}crlm_class_enrolment e, {$CFG->prefix}crlm_class cls, {$CFG->prefix}crlm_course c\n                     WHERE e.classid = cls.id\n                       AND cls.courseid = c.id\n                       AND e.credits = CAST(c.credits AS integer)";
        } else {
            $sql = "UPDATE {$CFG->prefix}crlm_class_enrolment e, {$CFG->prefix}crlm_class cls, {$CFG->prefix}crlm_course c\n                       SET e.credits = c.credits\n                     WHERE e.classid = cls.id\n                       AND cls.courseid = c.id\n                       AND e.credits = CAST(c.credits AS unsigned)";
        }
        $result = $result && execute_sql($sql);
    }
    if ($result && $oldversion < 2011050203) {
        //create a new column in the notification log table
        //to store the user who triggered the notification
        $table = new XMLDBTable('crlm_notification_log');
        $field = new XMLDBField('fromuserid');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, 0, 'userid');
        $field->comment = 'CM user id that triggered the notification.';
        $result = $result && add_field($table, $field);
        //populate data, assuming that the user who received the notification is the one whose
        //criteria spawned it
        //NOTE: this fudges data and the side-effect implies that if someone had received a notification
        //for another user and satisfy the same criteria for the same instance for themself, they will not
        //receive a similar notification
        $sql = "UPDATE {$CFG->prefix}crlm_notification_log\n                SET fromuserid = userid";
        $result = $result && execute_sql($sql);
        if ($result) {
            /// Define field certificatecode to be added to crlm_curriculum_assignment
            $table = new XMLDBTable('crlm_curriculum_assignment');
            $field = new XMLDBField('certificatecode');
            $field->setAttributes(XMLDB_TYPE_CHAR, '40', null, null, null, null, null, null, 'locked');
            /// Launch add field autocreated
            $result = $result && add_field($table, $field);
            /// Define index userid_ix (not unique) to be added to crlm_wait_list
            $index = new XMLDBIndex('certificatecode_ix');
            $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('certificatecode'));
            $result = $result && add_index($table, $index);
        }
    }
    if ($result && $oldversion < 2011050204) {
        $table = new XMLDBTable('crlm_notification_log');
        $index = new XMLDBIndex('event_inst_fuser_ix');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('fromuserid', 'instance', 'event'));
        $result = add_index($table, $index);
    }
    if ($result && $oldversion < 2011050205) {
        // Update the ELIS class enrolment grade value and completion score grade values so they store float
        // (decimal) values
        $table = new XMLDBTable('crlm_class_enrolment');
        $field = new XMLDBField('grade');
        $field->setAttributes(XMLDB_TYPE_NUMBER, '10', null, XMLDB_NOTNULL, null, null, null, '0');
        $field->setDecimals(5);
        $result = change_field_type($table, $field);
        $table = new XMLDBTable('crlm_class_graded');
        $result = $result && change_field_type($table, $field);
        /*
         * Find all of the completion grades that are synchronised from Moodle grade items that are not locked and
         * where the ELIS completion score does not match the value in the Moodle gradebook and delete those
         * completion scores so they can be re-synchronised from Moodle with the correct float values stored.
         */
        // Attempt to handle different DBs in the most efficient way possible
        if ($CFG->dbfamily == 'postgres') {
            $sql = "DELETE FROM {$CFG->prefix}crlm_class_graded\n                    WHERE id IN (\n                        SELECT ccg.id\n                        FROM mdl_crlm_user cu\n                        INNER JOIN {$CFG->prefix}crlm_class_enrolment cce ON cce.userid = cu.id\n                        INNER JOIN {$CFG->prefix}crlm_class_graded ccg ON (ccg.userid = cce.userid AND ccg.classid = cce.classid)\n                        INNER JOIN {$CFG->prefix}crlm_course_completion ccc ON ccc.id = ccg.completionid\n                        INNER JOIN {$CFG->prefix}crlm_class_moodle ccm ON ccm.classid = ccg.classid\n                        INNER JOIN {$CFG->prefix}user u ON u.idnumber = cu.idnumber\n                        INNER JOIN {$CFG->prefix}course c ON c.id = ccm.moodlecourseid\n                        INNER JOIN {$CFG->prefix}grade_items gi ON (gi.courseid = c.id AND gi.idnumber = ccc.idnumber)\n                        INNER JOIN {$CFG->prefix}grade_grades gg ON (gg.itemid = gi.id AND gg.userid = u.id)\n                        WHERE ccg.locked = 0\n                        AND ccc.idnumber != ''\n                        AND gi.itemtype != 'course'\n                        AND ccg.grade != gg.finalgrade\n                        AND gg.finalgrade IS NOT NULL\n                    )";
            $result = $result && execute_sql($sql);
        } else {
            if ($CFG->dbfamily == 'mysql') {
                $sql = "DELETE ccg\n                    FROM mdl_crlm_user cu\n                    INNER JOIN {$CFG->prefix}crlm_class_enrolment cce ON cce.userid = cu.id\n                    INNER JOIN {$CFG->prefix}crlm_class_graded ccg ON (ccg.userid = cce.userid AND ccg.classid = cce.classid)\n                    INNER JOIN {$CFG->prefix}crlm_course_completion ccc ON ccc.id = ccg.completionid\n                    INNER JOIN {$CFG->prefix}crlm_class_moodle ccm ON ccm.classid = ccg.classid\n                    INNER JOIN {$CFG->prefix}user u ON u.idnumber = cu.idnumber\n                    INNER JOIN {$CFG->prefix}course c ON c.id = ccm.moodlecourseid\n                    INNER JOIN {$CFG->prefix}grade_items gi ON (gi.courseid = c.id AND gi.idnumber = ccc.idnumber)\n                    INNER JOIN {$CFG->prefix}grade_grades gg ON (gg.itemid = gi.id AND gg.userid = u.id)\n                    WHERE ccg.locked = 0\n                    AND ccc.idnumber != ''\n                    AND gi.itemtype != 'course'\n                    AND ccg.grade != gg.finalgrade\n                    AND gg.finalgrade IS NOT NULL";
                $result = $result && execute_sql($sql);
            } else {
                $sql = "SELECT ccg.id, ccg.grade\n                    FROM mdl_crlm_user cu\n                    INNER JOIN {$CFG->prefix}crlm_class_enrolment cce ON cce.userid = cu.id\n                    INNER JOIN {$CFG->prefix}crlm_class_graded ccg ON (ccg.userid = cce.userid AND ccg.classid = cce.classid)\n                    INNER JOIN {$CFG->prefix}crlm_course_completion ccc ON ccc.id = ccg.completionid\n                    INNER JOIN {$CFG->prefix}crlm_class_moodle ccm ON ccm.classid = ccg.classid\n                    INNER JOIN {$CFG->prefix}user u ON u.idnumber = cu.idnumber\n                    INNER JOIN {$CFG->prefix}course c ON c.id = ccm.moodlecourseid\n                    INNER JOIN {$CFG->prefix}grade_items gi ON (gi.courseid = c.id AND gi.idnumber = ccc.idnumber)\n                    INNER JOIN {$CFG->prefix}grade_grades gg ON (gg.itemid = gi.id AND gg.userid = u.id)\n                    WHERE ccg.locked = 0\n                    AND ccc.idnumber != ''\n                    AND gi.itemtype != 'course'\n                    AND ccg.grade != gg.finalgrade\n                    AND gg.finalgrade IS NOT NULL";
                if ($rs = get_recordset_sql($sql)) {
                    while ($cg = rs_fetch_next_record($rs)) {
                        $result = $result && delete_records('crlm_class_graded', 'id', $cg->id);
                    }
                    rs_close($rs);
                }
            }
        }
        // Force a re-synchronization of ELIS class grade data
        require_once $CFG->dirroot . '/curriculum/lib/lib.php';
        cm_synchronize_moodle_class_grades();
    }
    if ($result && $oldversion < 2011050206) {
        /// Define table crlm_field_data to be dropped
        $table = new XMLDBTable('crlm_field_map');
        if (table_exists($table)) {
            /// Launch drop table for crlm_field_data
            $result = drop_table($table);
        }
    }
    if ($result && $oldversion < 2011050207) {
        // Delete duplicate class completion element grades
        $xmldbtable = new XMLDBTable('crlm_class_graded_temp');
        if (table_exists($xmldbtable)) {
            drop_table($xmldbtable);
        }
        // Create a temporary table
        $result = $result && execute_sql("CREATE TABLE {$CFG->prefix}crlm_class_graded_temp LIKE {$CFG->prefix}crlm_class_graded");
        // Store the unique values in the temporary table
        $sql = "INSERT INTO {$CFG->prefix}crlm_class_graded_temp\n                SELECT MAX(id) AS id, classid, userid, completionid, grade, locked, timegraded, timemodified\n                FROM {$CFG->prefix}crlm_class_graded\n                GROUP BY classid, userid, completionid, locked";
        $result = $result && execute_sql($sql);
        // Detect if there are still duplicates in the temporary table
        $sql = "SELECT COUNT(*) AS count, classid, userid, completionid, grade, locked, timegraded, timemodified\n                FROM {$CFG->prefix}crlm_class_graded_temp\n                GROUP BY classid, userid, completionid\n                ORDER BY count DESC, classid ASC, userid ASC, completionid ASC";
        if ($result && ($dupcount = get_record_sql($sql, true))) {
            if ($dupcount->count > 1) {
                if ($rs = get_recordset_sql($sql)) {
                    while ($result && ($dupe = rs_fetch_next_record($rs))) {
                        if ($dupe->count <= 1) {
                            continue;
                        }
                        $classid = $dupe->classid;
                        $userid = $dupe->userid;
                        $goodid = 0;
                        // The ID of the record we will keep
                        // Look for the earliest locked grade record for this user and keep that (if any are locked)
                        $sql2 = "SELECT id, grade, locked, timegraded\n                                 FROM mdl_crlm_class_graded\n                                 WHERE classid = {$classid}\n                                 AND userid = {$userid}\n                                 ORDER BY timegraded ASC";
                        if ($rs2 = get_recordset_sql($sql2)) {
                            while ($rec = rs_fetch_next_record($rs2)) {
                                // Store the last record ID just in case we need it for cleanup
                                $lastid = $rec->id;
                                // Don't bother looking at remaining records if we have found a record to keep
                                if (!empty($goodid)) {
                                    continue;
                                }
                                if ($rec->locked = 1) {
                                    $goodid = $rec->id;
                                }
                            }
                            rs_close($rs2);
                            // We need to make sure we have a record ID to keep, if we found no "complete" and locked
                            // records, let's just keep the last record we saw
                            if (empty($goodid)) {
                                $goodid = $lastid;
                            }
                            $select = 'classid = ' . $classid . ' AND userid = ' . $userid . ' AND id != ' . $goodid;
                        }
                        if (!empty($select)) {
                            $result = $result && delete_records_select('crlm_class_graded_temp', $select);
                        }
                    }
                }
            }
        }
        // Drop the real table
        $result = $result && execute_sql("DROP TABLE {$CFG->prefix}crlm_class_graded");
        // Replace the real table with the temporary table that now only contains unique values.
        $result = $result && execute_sql("ALTER TABLE {$CFG->prefix}crlm_class_graded_temp RENAME TO {$CFG->prefix}crlm_class_graded");
    }
    return $result;
}