/**
  * Ends a (possibly nested) transaction.
  */
 static function finish_transaction()
 {
     self::$transactions--;
     if (self::$transactions == 0) {
         commit_sql();
     }
 }
Ejemplo n.º 2
0
/**
 * Remove stale context records
 *
 * @return bool
 */
function cleanup_contexts()
{
    global $CFG;
    $sql = "  SELECT c.contextlevel,\n                     c.instanceid AS instanceid\n              FROM {$CFG->prefix}context c\n              LEFT OUTER JOIN {$CFG->prefix}course_categories t\n                ON c.instanceid = t.id\n              WHERE t.id IS NULL AND c.contextlevel = " . CONTEXT_COURSECAT . "\n            UNION\n              SELECT c.contextlevel,\n                     c.instanceid\n              FROM {$CFG->prefix}context c\n              LEFT OUTER JOIN {$CFG->prefix}course t\n                ON c.instanceid = t.id\n              WHERE t.id IS NULL AND c.contextlevel = " . CONTEXT_COURSE . "\n            UNION\n              SELECT c.contextlevel,\n                     c.instanceid\n              FROM {$CFG->prefix}context c\n              LEFT OUTER JOIN {$CFG->prefix}course_modules t\n                ON c.instanceid = t.id\n              WHERE t.id IS NULL AND c.contextlevel = " . CONTEXT_MODULE . "\n            UNION\n              SELECT c.contextlevel,\n                     c.instanceid\n              FROM {$CFG->prefix}context c\n              LEFT OUTER JOIN {$CFG->prefix}user t\n                ON c.instanceid = t.id\n              WHERE t.id IS NULL AND c.contextlevel = " . CONTEXT_USER . "\n            UNION\n              SELECT c.contextlevel,\n                     c.instanceid\n              FROM {$CFG->prefix}context c\n              LEFT OUTER JOIN {$CFG->prefix}block_instance t\n                ON c.instanceid = t.id\n              WHERE t.id IS NULL AND c.contextlevel = " . CONTEXT_BLOCK . "\n           ";
    if ($rs = get_recordset_sql($sql)) {
        begin_sql();
        $tx = true;
        while ($tx && ($ctx = rs_fetch_next_record($rs))) {
            $tx = $tx && delete_context($ctx->contextlevel, $ctx->instanceid);
        }
        rs_close($rs);
        if ($tx) {
            commit_sql();
            return true;
        }
        rollback_sql();
        return false;
        rs_close($rs);
    }
    return true;
}
Ejemplo n.º 3
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;
}
Ejemplo n.º 4
0
/**
 * Ensure all courses have a valid course category
 * useful if a category has been removed manually
 **/
function fix_coursecategory_orphans()
{
    global $CFG;
    // Note: the handling of sortorder here is arguably
    // open to race conditions. Hard to fix here, unlikely
    // to hit anyone in production.
    $sql = "SELECT c.id, c.category, c.shortname\n            FROM {$CFG->prefix}course c\n            LEFT OUTER JOIN {$CFG->prefix}course_categories cc ON c.category=cc.id\n            WHERE cc.id IS NULL AND c.id != " . SITEID;
    $rs = get_recordset_sql($sql);
    if (!rs_EOF($rs)) {
        // we have some orphans
        // the "default" category is the lowest numbered...
        $default = get_field_sql("SELECT MIN(id)\n                                    FROM {$CFG->prefix}course_categories");
        $sortorder = get_field_sql("SELECT MAX(sortorder)\n                                    FROM {$CFG->prefix}course\n                                    WHERE category={$default}");
        begin_sql();
        $tx = true;
        while ($tx && ($course = rs_fetch_next_record($rs))) {
            $tx = $tx && set_field('course', 'category', $default, 'id', $course->id);
            $tx = $tx && set_field('course', 'sortorder', ++$sortorder, 'id', $course->id);
        }
        if ($tx) {
            commit_sql();
        } else {
            rollback_sql();
        }
    }
    rs_close($rs);
}
 /**
  * Restores the data in the question
  *
  * This is used in question/restorelib.php
  */
 function restore($old_question_id, $new_question_id, $info, $restore)
 {
     $status = begin_sql();
     $minfo = $info['#']['MATRIX'];
     $newmatrix = (object) array('questionid' => $new_question_id, 'grademethod' => backup_todb($minfo[0]['#']['GRADEMETHOD']['0']['#']), 'multiple' => backup_todb($minfo[0]['#']['MULTIPLE']['0']['#']), 'renderer' => backup_todb($minfo[0]['#']['RENDERER']['0']['#']));
     $newmatrix->id = insert_record('question_matrix', $newmatrix);
     $rows = $minfo[0]['#']['ROWS'][0]['#']['ROW'];
     // why does this get eaten?!
     $rowmapping = array();
     foreach ($rows as $row) {
         $row = $row['#'];
         // more nonsense
         $newrow = (object) array('matrixid' => $newmatrix->id, 'shorttext' => backup_todb($row['SHORTTEXT']['0']['#']), 'description' => backup_todb($row['DESCRIPTION']['0']['#']), 'feedback' => backup_todb($row['FEEDBACK']['0']['#']));
         $status = $status && ($rowmapping[backup_todb($row['ID']['0']['#'])] = insert_record('question_matrix_rows', $newrow));
     }
     $cols = $minfo[0]['#']['COLS'][0]['#']['COL'];
     // why does this get eaten?!
     $colmapping = array();
     foreach ($cols as $col) {
         $col = $col['#'];
         // more nonsense
         $newcol = (object) array('matrixid' => $newmatrix->id, 'shorttext' => backup_todb($col['SHORTTEXT']['0']['#']), 'description' => backup_todb($col['DESCRIPTION']['0']['#']));
         $status = $status && ($colmapping[backup_todb($col['ID']['0']['#'])] = insert_record('question_matrix_cols', $newcol));
     }
     $weights = $minfo[0]['#']['WEIGHTS'][0]['#']['WEIGHT'];
     foreach ($weights as $weight) {
         $weight = $weight['#'];
         $newweight = (object) array('rowid' => $rowmapping[backup_todb($weight['ROWID'][0]['#'])], 'colid' => $colmapping[backup_todb($weight['COLID'][0]['#'])], 'weight' => backup_todb($weight['WEIGHT'][0]['#']));
         $status = $status && insert_record('question_matrix_weights', $newweight);
     }
     return $status && commit_sql();
 }
 /**
  * Adds a new document or updates an existing one. The necessary set_ 
  * methods must already have been called.
  * @param string $title Document title (plain text)
  * @param string $content Document content (XHTML)
  * @param int $timemodified Optional modified time (defaults to now)
  * @param int $timeexpires Optional expiry time (defaults to none); if
  *   expiry time is included then module must provide a 
  *   modulename_ousearch_update($document=null) function
  * @param mixed $extrastrings An array of additional strings which are
  *   searchable, but not included as part of the document content (for
  *   display to users etc). This can be used for keywords and the like
  * @return True for success, false for failure
  */
 function update($title, $content, $timemodified = null, $timeexpires = null, $extrastrings = null)
 {
     global $OUSEARCH_NO_TRANSACTIONS;
     if (empty($OUSEARCH_NO_TRANSACTIONS)) {
         begin_sql();
     }
     // Find document ID, creating document if needed
     if (!$this->find()) {
         // Arse around with slashes so we can insert it safely
         // but the data is corrected again later.
         if (!empty($this->stringref)) {
             $beforestringref = $this->stringref;
             $this->stringref = addslashes($this->stringref);
         }
         $beforeplugin = $this->plugin;
         $this->plugin = addslashes($this->plugin);
         $ok = insert_record('block_ousearch_documents', $this);
         if (!empty($beforestringref)) {
             $this->stringref = $beforestringref;
         }
         $this->plugin = $beforeplugin;
         if (!$ok) {
             debugging('Failed to add ousearch document');
             if (empty($OUSEARCH_NO_TRANSACTIONS)) {
                 rollback_sql();
             }
             return false;
         }
         $this->id = $ok;
     }
     // Update document record if needed
     if ($timemodified || $timeexpires) {
         $update = new StdClass();
         $update->id = $this->id;
         if ($timemodified) {
             $update->timemodified = $timemodified;
         }
         if ($timeexpires) {
             $update->timeexpires = $timeexpires;
         }
         if (!update_record('block_ousearch_documents', $update)) {
             debugging('Failed to update document record');
             if (empty($OUSEARCH_NO_TRANSACTIONS)) {
                 rollback_sql();
             }
             return false;
         }
     }
     // Delete existing words
     if (!delete_records('block_ousearch_occurrences', 'documentid', $this->id)) {
         debugging('Failed to delete occurrences for ousearch document ' . $this->id);
         if (empty($OUSEARCH_NO_TRANSACTIONS)) {
             rollback_sql();
         }
         return false;
     }
     // Extra strings are just counted as more content in the database
     if ($extrastrings) {
         foreach ($extrastrings as $string) {
             $content .= ' ' . $string;
         }
     }
     // Add new words
     $result = $this->internal_add_words($title, $content);
     if (empty($OUSEARCH_NO_TRANSACTIONS)) {
         commit_sql();
     }
     return $result;
 }
                            $resp_txt = new Ejercicios_texto_texto_resp(NULL, $id_pregunta, $resp_textarea, 0);
                            $resp_txt->insertar();
                        }
                    }
                    echo "insertado";
                }
            } else {
                if ($tipo_origen == 4) {
                    // ES UNA IMAGEN
                    if ($tipo_respuesta == 1) {
                        //La respuesta es un texto
                        //$preg = required_param('pregunta' . $j, PARAM_TEXT);
                        $preg = "foto_" . $id_ejercicio . "_" . $j . ".jpg";
                        $ejercicio_texto_preg = new Ejercicios_texto_texto_preg(NULL, $id_ejercicio, $preg);
                        $id_pregunta = $ejercicio_texto_preg->insertar();
                        $ejercicio_texto_img = new Ejercicios_imagenes_asociadas($NULL, $id_ejercicio, $id_pregunta, $preg);
                        $ejercicio_texto_img->insertar();
                        $num_resp = required_param('num_res_preg' . $j, PARAM_INT);
                        for ($k = 1; $k <= $num_resp; $k++) {
                            $resp_textarea = required_param("respuesta" . $k . "_" . $j, PARAM_TEXT);
                            $resp_txt = new Ejercicios_texto_texto_resp(NULL, $id_pregunta, $resp_textarea, 0);
                            $resp_txt->insertar();
                        }
                    }
                }
            }
        }
    }
}
commit_sql();
redirect('./view.php?id=' . $id_curso . '&opcion=9');
Ejemplo n.º 8
0
/**
 * Marks user deleted in internal user database and notifies the auth plugin.
 * Also unenrols user from all roles and does other cleanup.
 * @param object $user       Userobject before delete    (without system magic quotes)
 * @return boolean success
 */
function delete_user($user)
{
    global $CFG;
    require_once $CFG->libdir . '/grouplib.php';
    require_once $CFG->libdir . '/gradelib.php';
    require_once $CFG->dirroot . '/message/lib.php';
    begin_sql();
    // delete all grades - backup is kept in grade_grades_history table
    if ($grades = grade_grade::fetch_all(array('userid' => $user->id))) {
        foreach ($grades as $grade) {
            $grade->delete('userdelete');
        }
    }
    //move unread messages from this user to read
    message_move_userfrom_unread2read($user->id);
    // remove from all groups
    delete_records('groups_members', 'userid', $user->id);
    // unenrol from all roles in all contexts
    role_unassign(0, $user->id);
    // this might be slow but it is really needed - modules might do some extra cleanup!
    // now do a final accesslib cleanup - removes all role assingments in user context and context itself
    delete_context(CONTEXT_USER, $user->id);
    require_once $CFG->dirroot . '/tag/lib.php';
    tag_set('user', $user->id, array());
    // workaround for bulk deletes of users with the same email address
    $delname = addslashes("{$user->email}." . time());
    while (record_exists('user', 'username', $delname)) {
        // no need to use mnethostid here
        $delname++;
    }
    // mark internal user record as "deleted"
    $updateuser = new object();
    $updateuser->id = $user->id;
    $updateuser->deleted = 1;
    $updateuser->username = $delname;
    // Remember it just in case
    $updateuser->email = md5($user->username);
    // Store hash of username, useful importing/restoring users
    $updateuser->idnumber = '';
    // Clear this field to free it up
    $updateuser->timemodified = time();
    if (update_record('user', $updateuser)) {
        commit_sql();
        // notify auth plugin - do not block the delete even when plugin fails
        $authplugin = get_auth_plugin($user->auth);
        $authplugin->user_delete($user);
        events_trigger('user_deleted', $user);
        return true;
    } else {
        rollback_sql();
        return false;
    }
}
Ejemplo n.º 9
0
 /**
  * syncronizes user fron external db to moodle user table
  *
  * Sync is now using username attribute.
  *
  * Syncing users removes or suspends users that dont exists anymore in external db.
  * Creates new users and updates coursecreator status of users.
  *
  * @param int $bulk_insert_records will insert $bulkinsert_records per insert statement
  *                         valid only with $unsafe. increase to a couple thousand for
  *                         blinding fast inserts -- but test it: you may hit mysqld's
  *                         max_allowed_packet limit.
  * @param bool $do_updates will do pull in data updates from ldap if relevant
  */
 function sync_users($bulk_insert_records = 1000, $do_updates = true)
 {
     global $CFG;
     $textlib = textlib_get_instance();
     $droptablesql = array();
     /// sql commands to drop the table (because session scope could be a problem for
     /// some persistent drivers like ODBTP (mssql) or if this function is invoked
     /// from within a PHP application using persistent connections
     $temptable = $CFG->prefix . 'extuser';
     $createtemptablesql = '';
     // configure a temp table
     print "Configuring temp table\n";
     switch (strtolower($CFG->dbfamily)) {
         case 'mysql':
             $droptablesql[] = 'DROP TEMPORARY TABLE ' . $temptable;
             // sql command to drop the table (because session scope could be a problem)
             $createtemptablesql = 'CREATE TEMPORARY TABLE ' . $temptable . ' (username VARCHAR(64), PRIMARY KEY (username)) TYPE=MyISAM';
             break;
         case 'postgres':
             $droptablesql[] = 'DROP TABLE ' . $temptable;
             // sql command to drop the table (because session scope could be a problem)
             $bulk_insert_records = 1;
             // no support for multiple sets of values
             $createtemptablesql = 'CREATE TEMPORARY TABLE ' . $temptable . ' (username VARCHAR(64), PRIMARY KEY (username))';
             break;
         case 'mssql':
             $temptable = '#' . $temptable;
             /// MSSQL temp tables begin with #
             $droptablesql[] = 'DROP TABLE ' . $temptable;
             // sql command to drop the table (because session scope could be a problem)
             $bulk_insert_records = 1;
             // no support for multiple sets of values
             $createtemptablesql = 'CREATE TABLE ' . $temptable . ' (username VARCHAR(64), PRIMARY KEY (username))';
             break;
         case 'oracle':
             $droptablesql[] = 'TRUNCATE TABLE ' . $temptable;
             // oracle requires truncate before being able to drop a temp table
             $droptablesql[] = 'DROP TABLE ' . $temptable;
             // sql command to drop the table (because session scope could be a problem)
             $bulk_insert_records = 1;
             // no support for multiple sets of values
             $createtemptablesql = 'CREATE GLOBAL TEMPORARY TABLE ' . $temptable . ' (username VARCHAR(64), PRIMARY KEY (username)) ON COMMIT PRESERVE ROWS';
             break;
     }
     execute_sql_arr($droptablesql, true, false);
     /// Drop temp table to avoid persistence problems later
     echo "Creating temp table {$temptable}\n";
     if (!execute_sql($createtemptablesql, false)) {
         print "Failed to create temporary users table - aborting\n";
         exit;
     }
     print "Connecting to ldap...\n";
     $ldapconnection = $this->ldap_connect();
     if (!$ldapconnection) {
         $this->ldap_close();
         print get_string('auth_ldap_noconnect', 'auth', $this->config->host_url);
         exit;
     }
     ////
     //// get user's list from ldap to sql in a scalable fashion
     ////
     // prepare some data we'll need
     $filter = '(&(' . $this->config->user_attribute . '=*)' . $this->config->objectclass . ')';
     $contexts = explode(";", $this->config->contexts);
     if (!empty($this->config->create_context)) {
         array_push($contexts, $this->config->create_context);
     }
     $fresult = array();
     foreach ($contexts as $context) {
         $context = trim($context);
         if (empty($context)) {
             continue;
         }
         begin_sql();
         if ($this->config->search_sub) {
             //use ldap_search to find first user from subtree
             $ldap_result = ldap_search($ldapconnection, $context, $filter, array($this->config->user_attribute));
         } else {
             //search only in this context
             $ldap_result = ldap_list($ldapconnection, $context, $filter, array($this->config->user_attribute));
         }
         if ($entry = ldap_first_entry($ldapconnection, $ldap_result)) {
             do {
                 $value = ldap_get_values_len($ldapconnection, $entry, $this->config->user_attribute);
                 $value = $textlib->convert($value[0], $this->config->ldapencoding, 'utf-8');
                 // usernames are __always__ lowercase.
                 array_push($fresult, moodle_strtolower($value));
                 if (count($fresult) >= $bulk_insert_records) {
                     $this->ldap_bulk_insert($fresult, $temptable);
                     $fresult = array();
                 }
             } while ($entry = ldap_next_entry($ldapconnection, $entry));
         }
         unset($ldap_result);
         // free mem
         // insert any remaining users and release mem
         if (count($fresult)) {
             $this->ldap_bulk_insert($fresult, $temptable);
             $fresult = array();
         }
         commit_sql();
     }
     /// preserve our user database
     /// if the temp table is empty, it probably means that something went wrong, exit
     /// so as to avoid mass deletion of users; which is hard to undo
     $count = get_record_sql('SELECT COUNT(username) AS count, 1 FROM ' . $temptable);
     $count = $count->{'count'};
     if ($count < 1) {
         print "Did not get any users from LDAP -- error? -- exiting\n";
         exit;
     } else {
         print "Got {$count} records from LDAP\n\n";
     }
     /// User removal
     // find users in DB that aren't in ldap -- to be removed!
     // this is still not as scalable (but how often do we mass delete?)
     if (!empty($this->config->removeuser)) {
         $sql = "SELECT u.id, u.username, u.email, u.auth \n                    FROM {$CFG->prefix}user u\n                        LEFT JOIN {$temptable} e ON u.username = e.username\n                    WHERE u.auth='ldap'\n                        AND u.deleted=0\n                        AND e.username IS NULL";
         $remove_users = get_records_sql($sql);
         if (!empty($remove_users)) {
             print "User entries to remove: " . count($remove_users) . "\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";
                         }
                     }
                 }
             }
         } else {
             print "No user entries to be removed\n";
         }
         unset($remove_users);
         // free mem!
     }
     /// Revive suspended users
     if (!empty($this->config->removeuser) and $this->config->removeuser == 1) {
         $sql = "SELECT u.id, u.username\n                    FROM {$temptable} e, {$CFG->prefix}user u\n                    WHERE e.username=u.username\n                        AND u.auth='nologin'";
         $revive_users = get_records_sql($sql);
         if (!empty($revive_users)) {
             print "User entries to be revived: " . count($revive_users) . "\n";
             begin_sql();
             foreach ($revive_users as $user) {
                 $updateuser = new object();
                 $updateuser->id = $user->id;
                 $updateuser->auth = 'ldap';
                 if (update_record('user', $updateuser)) {
                     echo "\t";
                     print_string('auth_dbreviveser', 'auth', array($user->username, $user->id));
                     echo "\n";
                 } else {
                     echo "\t";
                     print_string('auth_dbreviveusererror', 'auth', $user->username);
                     echo "\n";
                 }
             }
             commit_sql();
         } else {
             print "No user entries to be revived\n";
         }
         unset($revive_users);
     }
     /// User Updates - time-consuming (optional)
     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 we have a field to update it from
                 // and it must be updated 'onlogin' we
                 // update it on cron
                 if (!empty($this->config->{'field_map_' . $match[1]}) and $this->config->{$match[0]} === 'onlogin') {
                     array_push($updatekeys, $match[1]);
                     // the actual key name
                 }
             }
         }
         // print_r($all_keys); print_r($updatekeys);
         unset($all_keys);
         unset($key);
     } else {
         print "No updates to be done\n";
     }
     if ($do_updates and !empty($updatekeys)) {
         // run updates only if relevant
         $users = get_records_sql("SELECT u.username, u.id\n                                      FROM {$CFG->prefix}user u\n                                      WHERE u.deleted=0 AND u.auth='ldap'");
         if (!empty($users)) {
             print "User entries to update: " . count($users) . "\n";
             $sitecontext = get_context_instance(CONTEXT_SYSTEM);
             if (!empty($this->config->creators) and !empty($this->config->memberattribute) and $roles = get_roles_with_capability('moodle/legacy:coursecreator', CAP_ALLOW)) {
                 $creatorrole = array_shift($roles);
                 // We can only use one, let's use the first one
             } else {
                 $creatorrole = false;
             }
             begin_sql();
             $xcount = 0;
             $maxxcount = 100;
             foreach ($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";
                 $xcount++;
                 // update course creators if needed
                 if ($creatorrole !== false) {
                     if ($this->iscreator($user->username)) {
                         role_assign($creatorrole->id, $user->id, 0, $sitecontext->id, 0, 0, 0, 'ldap');
                     } else {
                         role_unassign($creatorrole->id, $user->id, 0, $sitecontext->id, 'ldap');
                     }
                 }
                 if ($xcount++ > $maxxcount) {
                     commit_sql();
                     begin_sql();
                     $xcount = 0;
                 }
             }
             commit_sql();
             unset($users);
             // free mem
         }
     } else {
         // end do updates
         print "No updates to be done\n";
     }
     /// User Additions
     // find users missing in DB that are in LDAP
     // note that get_records_sql wants at least 2 fields returned,
     // and gives me a nifty object I don't want.
     // note: we do not care about deleted accounts anymore, this feature was replaced by suspending to nologin auth plugin
     $sql = "SELECT e.username, e.username\n                FROM {$temptable} e LEFT JOIN {$CFG->prefix}user u ON e.username = u.username\n                WHERE u.id IS NULL";
     $add_users = get_records_sql($sql);
     // get rid of the fat
     if (!empty($add_users)) {
         print "User entries to add: " . count($add_users) . "\n";
         $sitecontext = get_context_instance(CONTEXT_SYSTEM);
         if (!empty($this->config->creators) and !empty($this->config->memberattribute) and $roles = get_roles_with_capability('moodle/legacy:coursecreator', CAP_ALLOW)) {
             $creatorrole = array_shift($roles);
             // We can only use one, let's use the first one
         } else {
             $creatorrole = false;
         }
         begin_sql();
         foreach ($add_users as $user) {
             $user = $this->get_userinfo_asobj(addslashes($user->username));
             // prep a few params
             $user->modified = time();
             $user->confirmed = 1;
             $user->auth = 'ldap';
             $user->mnethostid = $CFG->mnet_localhost_id;
             // get_userinfo_asobj() might have replaced $user->username with the value
             // from the LDAP server (which can be mixed-case). Make sure it's lowercase
             $user->username = trim(moodle_strtolower($user->username));
             if (empty($user->lang)) {
                 $user->lang = $CFG->lang;
             }
             $user = addslashes_recursive($user);
             if ($id = insert_record('user', $user)) {
                 echo "\t";
                 print_string('auth_dbinsertuser', 'auth', array(stripslashes($user->username), $id));
                 echo "\n";
                 $userobj = $this->update_user_record($user->username);
                 if (!empty($this->config->forcechangepassword)) {
                     set_user_preference('auth_forcepasswordchange', 1, $userobj->id);
                 }
             } else {
                 echo "\t";
                 print_string('auth_dbinsertusererror', 'auth', $user->username);
                 echo "\n";
             }
             // add course creators if needed
             if ($creatorrole !== false and $this->iscreator(stripslashes($user->username))) {
                 role_assign($creatorrole->id, $user->id, 0, $sitecontext->id, 0, 0, 0, 'ldap');
             }
         }
         commit_sql();
         unset($add_users);
         // free mem
     } else {
         print "No users to be added\n";
     }
     $this->ldap_close();
     return true;
 }
Ejemplo n.º 10
0
function stats_upgrade_for_roles_wrapper()
{
    global $CFG;
    if (!empty($CFG->statsrolesupgraded)) {
        return true;
    }
    $result = begin_sql();
    $result = $result && stats_upgrade_user_table_for_roles('daily');
    $result = $result && stats_upgrade_user_table_for_roles('weekly');
    $result = $result && stats_upgrade_user_table_for_roles('monthly');
    $result = $result && stats_upgrade_table_for_roles('daily');
    $result = $result && stats_upgrade_table_for_roles('weekly');
    $result = $result && stats_upgrade_table_for_roles('monthly');
    $result = $result && commit_sql();
    if (!empty($result)) {
        set_config('statsrolesupgraded', time());
    }
    // finally upgade totals, no big deal if it fails
    stats_upgrade_totals();
    return $result;
}
Ejemplo n.º 11
0
/**
 * Actual implementation of the rest coures functionality, delete all the
 * quiz attempts for course $data->courseid, if $data->reset_quiz_attempts is
 * set and true.
 *
 * Also, move the quiz open and close dates, if the course start date is changing.
 *
 * @param $data the data submitted from the reset course forum.
 * @param $showfeedback whether to output progress information as the reset
 *      progresses.
 */
function quiz_delete_userdata($data, $showfeedback = true)
{
    global $CFG;
    /// Delete attempts.
    if (!empty($data->reset_quiz_attempts)) {
        $conditiononquizids = 'quiz IN (SELECT id FROM ' . $CFG->prefix . 'quiz q WHERE q.course = ' . $data->courseid . ')';
        $attemptids = get_records_select('quiz_attempts', $conditiononquizids, '', 'id, uniqueid');
        if ($attemptids) {
            if ($showfeedback) {
                echo '<div class="notifysuccess">', get_string('deletingquestionattempts', 'quiz');
                $divider = ': ';
            }
            foreach ($attemptids as $attemptid) {
                delete_attempt($attemptid->uniqueid);
                if ($showfeedback) {
                    echo $divider, $attemptid->uniqueid;
                    $divider = ', ';
                }
            }
            if ($showfeedback) {
                echo "</div><br />\n";
            }
        }
        if (delete_records_select('quiz_grades', $conditiononquizids) && $showfeedback) {
            notify(get_string('gradesdeleted', 'quiz'), 'notifysuccess');
        }
        if (delete_records_select('quiz_attempts', $conditiononquizids) && $showfeedback) {
            notify(get_string('attemptsdeleted', 'quiz'), 'notifysuccess');
        }
    }
    /// Update open and close dates
    if (!empty($data->reset_start_date)) {
        /// Work out offset.
        $olddate = get_field('course', 'startdate', 'id', $data->courseid);
        $olddate = usergetmidnight($olddate);
        // time part of $olddate should be zero
        $newdate = make_timestamp($data->startyear, $data->startmonth, $data->startday);
        $interval = $newdate - $olddate;
        /// Apply it to quizzes with an open or close date.
        $success = true;
        begin_sql();
        $success = $success && execute_sql("UPDATE {$CFG->prefix}quiz\n                    SET timeopen = timeopen + {$interval}\n                    WHERE course = {$data->courseid} AND timeopen <> 0", false);
        $success = $success && execute_sql("UPDATE {$CFG->prefix}quiz\n                    SET timeclose = timeclose + {$interval}\n                    WHERE course = {$data->courseid} AND timeclose <> 0", false);
        if ($success) {
            commit_sql();
            if ($showfeedback) {
                notify(get_string('openclosedatesupdated', 'quiz'), 'notifysuccess');
            }
        } else {
            rollback_sql();
        }
    }
}
Ejemplo n.º 12
0
 /**
  * syncronizes user fron external db to moodle user table
  *
  * Sync is now using username attribute.
  *
  * Syncing users removes or suspends users that dont exists anymore in external db.
  * Creates new users and updates coursecreator status of users.
  *
  * @param int $bulk_insert_records will insert $bulkinsert_records per insert statement
  *                         valid only with $unsafe. increase to a couple thousand for
  *                         blinding fast inserts -- but test it: you may hit mysqld's
  *                         max_allowed_packet limit.
  * @param bool $do_updates will do pull in data updates from ldap if relevant
  */
 function sync_users($bulk_insert_records = 1000, $do_updates = true)
 {
     global $CFG;
     // Set Debugging Mode
     ini_set('log_errors', true);
     $origdebug = $CFG->debug;
     $CFG->debug = DEBUG_DEVELOPER;
     // DEBUG_ALL, DEBUG_MINIMAL, DEBUG_DEVELOPER
     $CFG->debugdisplay = true;
     error_reporting($CFG->debug);
     // Debug All Errors Only
     $CFG->dblogerror = true;
     @set_time_limit(7200);
     // 2 hours should be enough
     @raise_memory_limit('512M');
     $textlib = textlib_get_instance();
     $droptablesql = array();
     /// sql commands to drop the table (because session scope could be a problem for
     /// some persistent drivers like ODBTP (mssql) or if this function is invoked
     /// from within a PHP application using persistent connections
     $temptable = $CFG->prefix . 'extuser';
     $createtemptablesql = '';
     // configure a temp table
     print "Configuring temp table\n";
     switch (strtolower($CFG->dbfamily)) {
         case 'mysql':
             $droptablesql[] = 'DROP TEMPORARY TABLE IF EXISTS ' . $temptable;
             // sql command to drop the table (because session scope could be a problem)
             $createtemptablesql = 'CREATE TEMPORARY TABLE ' . $temptable . ' (username VARCHAR(100), mnethostid BIGINT(10), PRIMARY KEY (username, mnethostid)) TYPE=MyISAM COLLATE utf8_general_ci';
             break;
         case 'postgres':
             $droptablesql[] = 'DROP TABLE ' . $temptable;
             // sql command to drop the table (because session scope could be a problem)
             $bulk_insert_records = 1;
             // no support for multiple sets of values
             $createtemptablesql = 'CREATE TEMPORARY TABLE ' . $temptable . '  (username VARCHAR(100), mnethostid INT(10), PRIMARY KEY (username, mnethostid)) COLLATE utf8_general_ci';
             break;
         case 'mssql':
             $temptable = '#' . $temptable;
             /// MSSQL temp tables begin with #
             $droptablesql[] = 'DROP TABLE ' . $temptable;
             // sql command to drop the table (because session scope could be a problem)
             $bulk_insert_records = 1;
             // no support for multiple sets of values
             $createtemptablesql = 'CREATE TABLE ' . $temptable . ' (username VARCHAR(100), mnethostid INT(10), PRIMARY KEY (username, mnethostid)) COLLATE utf8_general_ci';
             break;
         case 'oracle':
             $droptablesql[] = 'TRUNCATE TABLE ' . $temptable;
             // oracle requires truncate before being able to drop a temp table
             $droptablesql[] = 'DROP TABLE ' . $temptable;
             // sql command to drop the table (because session scope could be a problem)
             $bulk_insert_records = 1;
             // no support for multiple sets of values
             $createtemptablesql = 'CREATE GLOBAL TEMPORARY TABLE ' . $temptable . ' (username VARCHAR(100), mnethostid INT(10), PRIMARY KEY (username, mnethostid)) ON COMMIT PRESERVE ROWS';
             break;
     }
     print "Staring LDAP URL SSO Cron Sync - " . date(DATE_RFC822) . "\n";
     execute_sql_arr($droptablesql, true, false);
     /// Drop temp table to avoid persistence problems later
     echo "Creating temp table {$temptable}\n";
     if (!execute_sql($createtemptablesql, false)) {
         print "Failed to create temporary users table - aborting\n";
         exit;
     }
     print "Connecting to ldap...\n";
     $ldapconnection = $this->ldap_connect();
     if (!$ldapconnection) {
         @ldap_close($ldapconnection);
         print get_string('auth_ldap_noconnect', 'auth', $this->config->host_url);
         exit;
     }
     ////
     //// get user's list from ldap to sql in a scalable fashion
     ////
     // prepare some data we'll need
     $filter = '(&(' . $this->config->user_attribute . '=*) (' . $this->config->objectclass . '))';
     echo "filter: " . $filter . "\n";
     $contexts = explode(";", $this->config->contexts);
     if (!empty($this->config->create_context)) {
         array_push($contexts, $this->config->create_context);
     }
     $fresult = array();
     foreach ($contexts as $context) {
         $context = trim($context);
         if (empty($context)) {
             continue;
         }
         echo "Searching Context: " . $context . "\n";
         begin_sql();
         if ($this->config->search_sub) {
             //use ldap_search to find first user from subtree
             $ldap_result = ldap_search($ldapconnection, $context, $filter, array($this->config->user_attribute));
         } else {
             //search only in this context
             $ldap_result = ldap_list($ldapconnection, $context, $filter, array($this->config->user_attribute));
         }
         if ($entry = ldap_first_entry($ldapconnection, $ldap_result)) {
             do {
                 $value = ldap_get_values_len($ldapconnection, $entry, $this->config->user_attribute);
                 $value = $textlib->convert($value[0], $this->config->ldapencoding, 'utf-8');
                 // usernames are __always__ lowercase.
                 if (strpos($value[0], '$') && $this->config->user_type == 'ad') {
                     // Eliminiate AD Service Accounts
                     continue;
                 }
                 // Skip AD Service Account Entries
                 array_push($fresult, moodle_strtolower($value));
                 if (count($fresult) >= $bulk_insert_records) {
                     $this->ldap_bulk_insert($fresult, $temptable);
                     $fresult = array();
                 }
             } while ($entry = ldap_next_entry($ldapconnection, $entry));
         }
         unset($ldap_result);
         // free mem
         // insert any remaining users and release mem
         if (count($fresult)) {
             $this->ldap_bulk_insert($fresult, $temptable);
             $fresult = array();
         }
         commit_sql();
     }
     /// preserve our user database
     /// if the temp table is empty, it probably means that something went wrong, exit
     /// so as to avoid mass deletion of users; which is hard to undo
     $count = get_record_sql('SELECT COUNT(username) AS count, 1 FROM ' . $temptable);
     $count = $count->{'count'};
     if ($count < 1) {
         print "Did not get any users from LDAP -- error? -- exiting\n";
         exit;
     } else {
         print "Got {$count} records from LDAP\n\n";
     }
     /// User removal
     // find users in DB that aren't in ldap -- to be removed!
     // this is still not as scalable (but how often do we mass delete?)
     if (!empty($this->config->removeuser)) {
         $sql = "SELECT u.id, u.username, u.email, u.auth\r\n                    FROM {$CFG->prefix}user u\r\n                       LEFT JOIN {$temptable} e ON u.username = e.username\r\n                       AND u.mnethostid = e.mnethostid\r\n                    WHERE u.auth='ldapsso'\r\n                        AND u.deleted=0\r\n                        AND e.username IS NULL";
         $remove_users = get_records_sql($sql);
         if (!empty($remove_users)) {
             print "User entries to remove: " . count($remove_users) . "\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";
                         }
                     }
                 }
             }
         } else {
             print "No user entries to be removed\n";
         }
         unset($remove_users);
         // free mem!
     }
     /// Revive suspended users
     if (!empty($this->config->removeuser) and $this->config->removeuser == 1) {
         $sql = "SELECT u.id, u.username\r\n                    FROM {$temptable} e, {$CFG->prefix}user u\r\n                    WHERE e.username=u.username\r\n                    AND e.mnethostid=u.mnethostid\r\n                    AND u.auth='nologin'";
         $revive_users = get_records_sql($sql);
         if (!empty($revive_users)) {
             print "User entries to be revived: " . count($revive_users) . "\n";
             begin_sql();
             foreach ($revive_users as $user) {
                 $updateuser = new object();
                 $updateuser->id = $user->id;
                 $updateuser->auth = 'ldap';
                 if (update_record('user', $updateuser)) {
                     echo "\t";
                     print_string('auth_ldap_sso_dbreviveuser', 'auth_ldapsso', array($user->username, $user->id));
                     echo "\n";
                 } else {
                     echo "\t";
                     print_string('auth_ldap_sso_dbreviveusererror', 'auth_ldapsso', $user->username);
                     echo "\n";
                 }
             }
             commit_sql();
         } else {
             print "No user entries to be revived\n";
         }
         unset($revive_users);
     }
     /// User Updates - time-consuming (optional)
     if ($do_updates) {
         // narrow down what fields we need to update
         $all_keys = array_keys(get_object_vars($this->config));
         $updatekeys = array();
         // $updatekeys = array('firstname','lastname','idnumber');
         foreach ($all_keys as $key) {
             if (preg_match('/^field_updatelocal_(.+)$/', $key, $match)) {
                 // if we have a field to update it from
                 // and it must be updated 'onlogin' we
                 // update it on cron
                 if (!empty($this->config->{'field_map_' . $match[1]}) and $this->config->{$match[0]} === 'onlogin') {
                     array_push($updatekeys, $match[1]);
                     // the actual key name
                 }
             }
         }
         // print_r($all_keys); print_r($updatekeys);
         unset($all_keys);
         unset($key);
     } else {
         print "No updates to be done\n";
     }
     if ($do_updates and !empty($updatekeys)) {
         // run updates only if relevant
         $users = get_records_sql("SELECT u.username, u.id\r\n                                      FROM {$CFG->prefix}user u\r\n                                      WHERE u.deleted=0 AND u.auth='ldapsso'");
         if (!empty($users)) {
             print "User entries to update: " . count($users) . "\n";
             $sitecontext = get_context_instance(CONTEXT_SYSTEM);
             if (!empty($this->config->creators) and !empty($this->config->memberattribute) and $roles = get_roles_with_capability('moodle/legacy:coursecreator', CAP_ALLOW)) {
                 $creatorrole = array_shift($roles);
                 // We can only use one, let's use the first one
             } else {
                 $creatorrole = false;
             }
             begin_sql();
             $xcount = 0;
             $maxxcount = 100;
             foreach ($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";
                 $xcount++;
                 // update course creators if needed
                 if ($creatorrole !== false) {
                     if ($this->iscreator($user->username)) {
                         role_assign($creatorrole->id, $user->id, 0, $sitecontext->id, 0, 0, 0, 'ldap');
                     } else {
                         role_unassign($creatorrole->id, $user->id, 0, $sitecontext->id, 'ldap');
                     }
                 }
                 if ($xcount++ > $maxxcount) {
                     commit_sql();
                     begin_sql();
                     $xcount = 0;
                 }
             }
             commit_sql();
             unset($users);
             // free mem
         }
     }
     /// Switch users that exist in extauth and Moodle that are currently using alternate login
     print "Validating user authentication method for LDAP SSO users.\n";
     $sql = "SELECT u.id, u.auth, e.username\r\n              FROM {$temptable} e JOIN {$CFG->prefix}user u ON e.username = u.username\r\n              AND e.mnethostid = u.mnethostid\r\n              WHERE u.id IS NOT NULL AND u.auth!='ldapsso'";
     $mauth_users = get_records_sql($sql);
     if (!empty($mauth_users)) {
         print "Users entries to update with ldap auth: " . count($mauth_users) . "\n";
         begin_sql();
         foreach ($mauth_users as $user) {
             echo "\t";
             print_string('auth_dbupdatinguser', 'auth', array($user->username, $user->id));
             echo "\n";
             // get the current user record
             $user = get_record('user', 'username', addslashes($user->username), 'auth', $user->auth);
             if (!empty($user)) {
                 set_field('user', 'auth', 'ldapsso', 'id', $user->id);
             } else {
                 echo "\t";
                 print 'Cannot switch $user->auth user : ' . $user->username . ' to LDAP auth!';
                 echo "\n";
             }
         }
         commit_sql();
         unset($mauth_users);
         // free mem
     } else {
         print "No users found to be updated!\n";
     }
     /// User Additions
     // find users missing in DB that are in LDAP
     // note that get_records_sql wants at least 2 fields returned,
     // and gives me a nifty object I don't want.
     // note: we do not care about deleted accounts anymore, this feature was replaced by suspending to nologin auth plugin
     print "Checking for User Additions\n";
     $sql = "SELECT e.username AS user, e.username\r\n                FROM {$temptable} e LEFT JOIN {$CFG->prefix}user u ON e.username = u.username\r\n                AND e.mnethostid = u.mnethostid\r\n                WHERE u.id IS NULL";
     $add_users = get_records_sql($sql);
     // get rid of the fat
     if (!empty($add_users)) {
         print "User entries to add: " . count($add_users) . "\n";
         $sitecontext = get_context_instance(CONTEXT_SYSTEM);
         if (!empty($this->config->creators) and !empty($this->config->memberattribute) and $roles = get_roles_with_capability('moodle/legacy:coursecreator', CAP_ALLOW)) {
             $creatorrole = array_shift($roles);
             // We can only use one, let's use the first one
         } else {
             $creatorrole = false;
         }
         begin_sql();
         foreach ($add_users as $user) {
             if (!isset($user->username) || empty($user->username)) {
                 continue;
             }
             $username = $user->username;
             // Allow . (dot char) in name
             $user = $this->get_userinfo_asobj(addslashes($user->username));
             // prep a few params
             $user->modified = time();
             $user->confirmed = 1;
             $user->auth = 'ldapsso';
             $user->username = $username;
             $user->mnethostid = $CFG->mnet_localhost_id;
             if (empty($user->lang)) {
                 $user->lang = $CFG->lang;
             }
             $user = addslashes_recursive($user);
             if ($id = insert_record('user', $user)) {
                 echo "\t";
                 print_string('auth_dbinsertuser', 'auth', array(stripslashes($user->username), $id));
                 echo "\n";
                 $userobj = $this->update_user_record($user->username);
                 if (!empty($this->config->forcechangepassword)) {
                     set_user_preference('auth_forcepasswordchange', 1, $userobj->id);
                 }
             } else {
                 echo "\t";
                 print_string('auth_dbinsertusererror', 'auth', $user->username);
                 echo "\n";
             }
             // add course creators if needed
             if ($creatorrole !== false and $this->iscreator(stripslashes($user->username))) {
                 role_assign($creatorrole->id, $user->id, 0, $sitecontext->id, 0, 0, 0, 'ldap');
             }
         }
         commit_sql();
         unset($add_users);
         // free mem
     } else {
         print "No users to be added\n";
     }
     // Return to original debugging level
     $CFG->debug = $origdebug;
     error_reporting($CFG->debug);
     $CFG->dblogerror = false;
     @ldap_close($ldapconnection);
     print "LDAP URL SSO Cron Sync completed - " . date(DATE_RFC822) . "\n";
     return true;
 }
Ejemplo n.º 13
0
function dialogue_delete_conversation($dialogueid, $conversationid)
{
    //echo "<div style=\"text-align:center;\">deleting dialogue $dialogueid and conversation $conversationid</div>";
    begin_sql();
    //$tx = true; // transaction sanity
    $tx = delete_records("dialogue_conversations", "id", $conversationid, "dialogueid", $dialogueid);
    $tx = $tx && delete_records("dialogue_entries", "conversationid", $conversationid, "dialogueid", $dialogueid);
    if ($tx) {
        commit_sql();
    } else {
        rollback_sql();
        error("oups...error deleting conversation");
        return false;
    }
    return true;
}
Ejemplo n.º 14
0
/**
 * Process Job's results logged in a text file.
 * 
 * @param array $scan from table blended_scans
 */
function register_scannedjob($scan)
{
    global $CFG;
    global $scansfoldername;
    $jobid = $scan->id;
    $fieldspath = blended_getOMRFieldsetDir($scan);
    $logfile = blended_getOMRInputLogFilePath($scan);
    try {
        if ($logfile != 'null') {
            $logelements = read_log_file($logfile);
        }
        if (!isset($logelements) || count($logelements) == 0) {
            throw new OMRError("Log file is empty", OMRError::LOG_FILE_IS_EMPTY);
        }
    } catch (OMRError $e) {
        throw $e;
    }
    // open a transaction
    begin_sql();
    foreach ($logelements as $logelement) {
        try {
            //cada elemento es un registro de blended_images.
            $image_result = parse_log_elements($logelement);
            $image_result->jobid = $jobid;
            register_image($image_result);
            $acode = $image_result->activitycode;
            if ($acode != null) {
                if ($acode == 'Undetected') {
                    mtrace("Undetected activity code for result:" . $logelement);
                } else {
                    mtrace('<br>REGISTERING FIELDS...');
                    register_template_fields($image_result, $fieldspath);
                    mtrace('<br>REGISTERING RESULTS...');
                    register_result_files($image_result, $fieldspath);
                    mtrace('<br>CHECKING VALIDITY...');
                    check_invalid_results($image_result);
                }
            }
        } catch (Exception $e) {
            mtrace('OMRError: ' . $e->getMessage());
            register_exception($e, $jobid);
            $errorcode = $e->getCode();
            if ($errorcode == 5 or $errorcode == 6) {
                //print_object($e);
                //throw $e;
                continue;
                // process next result
            }
        }
    }
    mtrace('<br>UPDATING SCANJOB QUEUE...');
    update_record('blended_scans', $scan);
    // End the transaction
    commit_sql();
    return;
}
Ejemplo n.º 15
0
function quiz_upgrade($oldversion)
{
    // This function does anything necessary to upgrade
    // older versions to match current functionality
    global $CFG, $db;
    $success = true;
    include_once "{$CFG->dirroot}/mod/quiz/locallib.php";
    if ($success && $oldversion < 2003010100) {
        $success = $success && execute_sql(" ALTER TABLE {$CFG->prefix}quiz ADD review integer DEFAULT '0' NOT NULL AFTER `grademethod` ");
    }
    if ($success && $oldversion < 2003010301) {
        $success = $success && table_column("quiz_truefalse", "true", "trueanswer", "INTEGER", "10", "UNSIGNED", "0", "NOT NULL", "");
        $success = $success && table_column("quiz_truefalse", "false", "falseanswer", "INTEGER", "10", "UNSIGNED", "0", "NOT NULL", "");
        $success = $success && table_column("quiz_questions", "type", "qtype", "INTEGER", "10", "UNSIGNED", "0", "NOT NULL", "");
    }
    if ($success && $oldversion < 2003022303) {
        $success = $success && modify_database("", "CREATE TABLE prefix_quiz_randommatch (\n                                  id SERIAL PRIMARY KEY,\n                                  question integer NOT NULL default '0',\n                                  choose integer NOT NULL default '4'\n                              );");
    }
    if ($success && $oldversion < 2003030303) {
        $success = $success && table_column("quiz_questions", "", "defaultgrade", "INTEGER", "6", "UNSIGNED", "1", "NOT NULL", "image");
    }
    if ($success && $oldversion < 2003033100) {
        $success = $success && modify_database("", "ALTER TABLE prefix_quiz_randommatch RENAME prefix_quiz_randomsamatch ");
        $success = $success && modify_database("", "CREATE TABLE prefix_quiz_match_sub (\n                                 id SERIAL PRIMARY KEY,\n                                 question integer NOT NULL default '0',\n                                 questiontext text NOT NULL default '',\n                                 answertext varchar(255) NOT NULL default ''\n                              );");
        $success = $success && modify_database("", "CREATE INDEX prefix_quiz_match_sub_question_idx ON prefix_quiz_match_sub (question);");
        $success = $success && modify_database("", "CREATE TABLE prefix_quiz_multichoice (\n                                 id SERIAL PRIMARY KEY,\n                                 question integer NOT NULL default '0',\n                                 layout integer NOT NULL default '0',\n                                 answers varchar(255) NOT NULL default '',\n                                 single integer NOT NULL default '0'\n                               );");
        $success = $success && modify_database("", "CREATE INDEX prefix_quiz_multichoice_question_idx ON prefix_quiz_multichoice (question);");
    }
    if ($success && $oldversion < 2003040901) {
        $success = $success && table_column("quiz", "", "shufflequestions", "INTEGER", "5", "UNSIGNED", "0", "NOT NULL", "review");
        $success = $success && table_column("quiz", "", "shuffleanswers", "INTEGER", "4", "UNSIGNED", "0", "NOT NULL", "shufflequestions");
    }
    if ($success && $oldversion < 2003042702) {
        $success = $success && modify_database("", "CREATE TABLE prefix_quiz_match (\n                                 id SERIAL PRIMARY KEY,\n                                 question integer NOT NULL default '0',\n                                 subquestions varchar(255) NOT NULL default ''\n                               );");
        $success = $success && modify_database("", "CREATE INDEX prefix_quiz_match_question_idx ON prefix_quiz_match (question);");
    }
    if ($success && $oldversion < 2003071001) {
        $success = $success && modify_database("", " CREATE TABLE prefix_quiz_numerical (\n                               id SERIAL PRIMARY KEY,\n                               question integer NOT NULL default '0',\n                               answer integer NOT NULL default '0',\n                               min varchar(255) NOT NULL default '',\n                               max varchar(255) NOT NULL default ''\n                               ); ");
        $success = $success && modify_database("", "CREATE INDEX prefix_quiz_numerical_answer_idx ON prefix_quiz_numerical (answer);");
    }
    if ($success && $oldversion < 2003072400) {
        $success = $success && execute_sql(" INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('quiz', 'review', 'quiz', 'name') ");
    }
    if ($success && $oldversion < 2003082300) {
        $success = $success && modify_database("", " CREATE TABLE prefix_quiz_multianswers (\n                               id SERIAL PRIMARY KEY,\n                               question integer NOT NULL default '0',\n                               answers varchar(255) NOT NULL default '',\n                               positionkey varchar(255) NOT NULL default '',\n                               answertype integer NOT NULL default '0',\n                               norm integer NOT NULL default '1'\n                              ); ");
        $success = $success && modify_database("", "CREATE INDEX prefix_quiz_multianswers_question_idx ON prefix_quiz_multianswers (question);");
        $success = $success && table_column("quiz", "", "attemptonlast", "INTEGER", "10", "UNSIGNED", "0", "NOT NULL", "attempts");
        $success = $success && table_column("quiz_questions", "", "stamp", "varchar", "255", "", "qtype");
    }
    if ($success && $oldversion < 2003082301) {
        $success = $success && table_column("quiz_questions", "", "version", "integer", "10", "", "1", "not null", "stamp");
        if ($questions = get_records("quiz_questions")) {
            foreach ($questions as $question) {
                $stamp = make_unique_id_code();
                if (!($success = $success && set_field("quiz_questions", "stamp", $stamp, "id", $question->id))) {
                    notify("Error while adding stamp to question id = {$question->id}");
                    break;
                }
            }
        }
    }
    if ($success && $oldversion < 2003082700) {
        table_column("quiz_categories", "", "stamp", "varchar", "255", "", "", "not null");
        if ($categories = get_records("quiz_categories")) {
            foreach ($categories as $category) {
                $stamp = make_unique_id_code();
                if (!($success = $success && set_field("quiz_categories", "stamp", $stamp, "id", $category->id))) {
                    notify("Error while adding stamp to category id = {$category->id}");
                    break;
                }
            }
        }
    }
    if ($success && $oldversion < 2003111100) {
        $duplicates = get_records_sql("SELECT stamp as id,count(*) as cuenta\n                                       FROM {$CFG->prefix}quiz_questions\n                                       GROUP BY stamp\n                                       HAVING count(*)>1");
        if ($duplicates) {
            notify("You have some quiz questions with duplicate stamps IDs.  Cleaning these up.");
            foreach ($duplicates as $duplicate) {
                $questions = get_records("quiz_questions", "stamp", $duplicate->id);
                $add = 1;
                foreach ($questions as $question) {
                    echo "Changing question id {$question->id} stamp to " . $duplicate->id . $add . "<br />";
                    $success = $success && set_field("quiz_questions", "stamp", $duplicate->id . $add, "id", $question->id);
                    $add++;
                }
            }
        } else {
            notify("Checked your quiz questions for stamp duplication errors, but no problems were found.", "green");
        }
    }
    if ($success && $oldversion < 2004021300) {
        $success = $success && table_column("quiz_questions", "", "questiontextformat", "integer", "2", "", "0", "not null", "questiontext");
    }
    if ($success && $oldversion < 2004021900) {
        $success = $success && modify_database("", "INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('quiz', 'add', 'quiz', 'name');");
        $success = $success && modify_database("", "INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('quiz', 'update', 'quiz', 'name');");
    }
    if ($success && $oldversion < 2004051700) {
        include_once "{$CFG->dirroot}/mod/quiz/lib.php";
        $success = $success && quiz_refresh_events();
    }
    if ($success && $oldversion < 2004060200) {
        $success = $success && table_column("quiz", "", "timelimit", "integer", "", "", "0", "NOT NULL", "");
    }
    if ($success && $oldversion < 2004070700) {
        $success = $success && table_column("quiz", "", "password", "varchar", "255", "", "", "not null", "");
        $success = $success && table_column("quiz", "", "subnet", "varchar", "255", "", "", "not null", "");
    }
    if ($success && $oldversion < 2004073001) {
        // Six new tables:
        $success = $success && modify_database("", "BEGIN;");
        // One table for handling units for numerical questions
        $success = $success && modify_database("", " CREATE TABLE prefix_quiz_numerical_units (\n                               id SERIAL8 PRIMARY KEY,\n                               question INT8  NOT NULL default '0',\n                               multiplier decimal(40,20) NOT NULL default '1.00000000000000000000',\n                               unit varchar(50) NOT NULL default ''\n                );");
        // Four tables for handling distribution and storage of
        // individual data for dataset dependent question types
        $success = $success && modify_database("", " CREATE TABLE prefix_quiz_attemptonlast_datasets (\n                               id SERIAL8 PRIMARY KEY,\n                               category INT8  NOT NULL default '0',\n                               userid INT8  NOT NULL default '0',\n                               datasetnumber INT8  NOT NULL default '0',\n                               CONSTRAINT prefix_quiz_attemptonlast_datasets_category_userid UNIQUE (category,userid)\n            ) ;");
        $success = $success && modify_database("", " CREATE TABLE prefix_quiz_dataset_definitions (\n                               id SERIAL8 PRIMARY KEY,\n                               category INT8  NOT NULL default '0',\n                               name varchar(255) NOT NULL default '',\n                               type INT8 NOT NULL default '0',\n                               options varchar(255) NOT NULL default '',\n                               itemcount INT8  NOT NULL default '0'\n            ) ; ");
        $success = $success && modify_database("", " CREATE TABLE prefix_quiz_dataset_items (\n                               id SERIAL8 PRIMARY KEY,\n                               definition INT8  NOT NULL default '0',\n                               number INT8  NOT NULL default '0',\n                               value varchar(255) NOT NULL default ''\n                             ) ; ");
        $success = $success && modify_database("", "CREATE INDEX prefix_quiz_dataset_items_definition_idx ON prefix_quiz_dataset_items (definition);");
        $success = $success && modify_database("", " CREATE TABLE prefix_quiz_question_datasets (\n                               id SERIAL8 PRIMARY KEY,\n                               question INT8  NOT NULL default '0',\n                               datasetdefinition INT8  NOT NULL default '0'\n            ) ; ");
        $success = $success && modify_database("", "CREATE INDEX prefix_quiz_question_datasets_question_datasetdefinition_idx ON prefix_quiz_question_datasets (question,datasetdefinition);");
        // One table for new question type calculated
        //  - the first dataset dependent question type
        $success = $success && modify_database("", " CREATE TABLE prefix_quiz_calculated (\n                               id SERIAL8 PRIMARY KEY,\n                               question INT8  NOT NULL default '0',\n                               answer INT8  NOT NULL default '0',\n                               tolerance varchar(20) NOT NULL default '0.0',\n                               tolerancetype INT8 NOT NULL default '1',\n                               correctanswerlength INT8 NOT NULL default '2'\n                ) ; ");
        $success = $success && modify_database("", "CREATE INDEX prefix_quiz_calculated_question_idx ON  prefix_quiz_calculated (question);");
        $success = $success && modify_database("", "COMMIT;");
    }
    if ($success && $oldversion < 2004111400) {
        $success = $success && table_column("quiz_responses", "answer", "answer", "text", "", "", "", "not null");
    }
    if ($success && $oldversion < 2004111700) {
        $success = $success && execute_sql("DROP INDEX {$CFG->prefix}quiz_course_idx;", false);
        $success = $success && execute_sql("DROP INDEX {$CFG->prefix}quiz_answers_question_idx;", false);
        $success = $success && execute_sql("DROP INDEX {$CFG->prefix}quiz_attempts_quiz_idx;", false);
        $success = $success && execute_sql("DROP INDEX {$CFG->prefix}quiz_attempts_userid_idx;", false);
        $success = $success && execute_sql("DROP INDEX {$CFG->prefix}quiz_calculated_answer_idx;", false);
        $success = $success && execute_sql("DROP INDEX {$CFG->prefix}quiz_categories_course_idx;", false);
        $success = $success && execute_sql("DROP INDEX {$CFG->prefix}quiz_dataset_definitions_category_idx;", false);
        $success = $success && execute_sql("DROP INDEX {$CFG->prefix}quiz_grades_quiz_idx;", false);
        $success = $success && execute_sql("DROP INDEX {$CFG->prefix}quiz_grades_userid_idx;", false);
        $success = $success && execute_sql("DROP INDEX {$CFG->prefix}quiz_numerical_question_idx;", false);
        $success = $success && execute_sql("DROP INDEX {$CFG->prefix}quiz_numerical_units_question_idx;", false);
        $success = $success && execute_sql("DROP INDEX {$CFG->prefix}quiz_question_grades_quiz_idx;", false);
        $success = $success && execute_sql("DROP INDEX {$CFG->prefix}quiz_question_grades_question_idx;", false);
        $success = $success && execute_sql("DROP INDEX {$CFG->prefix}quiz_questions_category_idx;", false);
        $success = $success && execute_sql("DROP INDEX {$CFG->prefix}quiz_randomsamatch_question_idx;", false);
        $success = $success && execute_sql("DROP INDEX {$CFG->prefix}quiz_responses_attempt_idx;", false);
        $success = $success && execute_sql("DROP INDEX {$CFG->prefix}quiz_responses_question_idx;", false);
        $success = $success && modify_database('', 'CREATE INDEX prefix_quiz_course_idx ON prefix_quiz (course);');
        $success = $success && modify_database('', 'CREATE INDEX prefix_quiz_answers_question_idx ON prefix_quiz_answers (question);');
        $success = $success && modify_database('', 'CREATE INDEX prefix_quiz_attempts_quiz_idx ON prefix_quiz_attempts (quiz);');
        $success = $success && modify_database('', 'CREATE INDEX prefix_quiz_attempts_userid_idx ON prefix_quiz_attempts (userid);');
        $success = $success && modify_database('', 'CREATE INDEX prefix_quiz_calculated_answer_idx ON prefix_quiz_calculated (answer);');
        $success = $success && modify_database('', 'CREATE INDEX prefix_quiz_categories_course_idx ON prefix_quiz_categories (course);');
        $success = $success && modify_database('', 'CREATE INDEX prefix_quiz_dataset_definitions_category_idx ON prefix_quiz_dataset_definitions (category);');
        $success = $success && modify_database('', 'CREATE INDEX prefix_quiz_grades_quiz_idx ON prefix_quiz_grades (quiz);');
        $success = $success && modify_database('', 'CREATE INDEX prefix_quiz_grades_userid_idx ON prefix_quiz_grades (userid);');
        $success = $success && modify_database('', 'CREATE INDEX prefix_quiz_numerical_question_idx ON prefix_quiz_numerical (question);');
        $success = $success && modify_database('', 'CREATE INDEX prefix_quiz_numerical_units_question_idx ON prefix_quiz_numerical_units (question);');
        $success = $success && modify_database('', 'CREATE INDEX prefix_quiz_question_grades_quiz_idx ON prefix_quiz_question_grades (quiz);');
        $success = $success && modify_database('', 'CREATE INDEX prefix_quiz_question_grades_question_idx ON prefix_quiz_question_grades (question);');
        $success = $success && modify_database('', 'CREATE INDEX prefix_quiz_questions_category_idx ON prefix_quiz_questions (category);');
        $success = $success && modify_database('', 'CREATE INDEX prefix_quiz_randomsamatch_question_idx ON prefix_quiz_randomsamatch (question);');
        $success = $success && modify_database('', 'CREATE INDEX prefix_quiz_responses_attempt_idx ON prefix_quiz_responses (attempt);');
        $success = $success && modify_database('', 'CREATE INDEX prefix_quiz_responses_question_idx ON prefix_quiz_responses (question);');
    }
    if ($success && $oldversion < 2004112300) {
        //try and clean up an old mistake - try and bring us up to what is in postgres7.sql today.
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_attemptonlast_datasets DROP CONSTRAINT category;", false);
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_attemptonlast_datasets DROP CONSTRAINT {$CFG->prefix}quiz_attemptonlast_datasets_category_userid;", false);
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_attemptonlast_datasets DROP CONSTRAINT {$CFG->prefix}quiz_category_userid_unique;", false);
        $success = $success && modify_database('', 'ALTER TABLE prefix_quiz_attemptonlast_datasets ADD CONSTRAINT prefix_quiz_category_userid_unique UNIQUE (category,userid);');
    }
    if ($success && $oldversion < 2004120501) {
        $success = $success && table_column("quiz_calculated", "", "correctanswerformat", "integer", "10", "", "0", "not null", "correctanswerlength");
    }
    if ($success && $oldversion < 2004121400) {
        // New field to determine popup window behaviour
        $success = $success && table_column("quiz", "", "popup", "integer", "4", "", "0", "not null", "subnet");
    }
    if ($success && $oldversion < 2005010201) {
        $success = $success && table_column('quiz_categories', '', 'parent');
        $success = $success && table_column('quiz_categories', '', 'sortorder', 'integer', '10', '', '999');
    }
    if ($success && $oldversion < 2005010300) {
        $success = $success && table_column("quiz", "", "questionsperpage", "integer", "10", "", "0", "not null", "review");
    }
    if ($success && $oldversion < 2005012700) {
        $success = $success && table_column('quiz_grades', 'grade', 'grade', 'real', 2, '');
    }
    if ($success && $oldversion < 2005021400) {
        $success = $success && table_column("quiz", "", "decimalpoints", "integer", "4", "", "2", "not null", "grademethod");
    }
    if ($success && $oldversion < 2005022800) {
        $success = $success && table_column('quiz_questions', '', 'hidden', 'integer', '1', 'unsigned', '0', 'not null', 'version');
        $success = $success && table_column('quiz_responses', '', 'originalquestion', 'integer', '10', 'unsigned', '0', 'not null', 'question');
        $success = $success && modify_database('', "CREATE TABLE prefix_quiz_question_version (\n                              id SERIAL PRIMARY KEY,\n                              quiz integer NOT NULL default '0',\n                              oldquestion integer NOT NULL default '0',\n                              newquestion integer NOT NULL default '0',\n                              userid integer NOT NULL default '0',\n                              timestamp integer NOT NULL default '0');");
    }
    if ($success && $oldversion < 2005032000) {
        $success = $success && execute_sql(" INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('quiz', 'editquestions', 'quiz', 'name') ");
    }
    if ($success && $oldversion < 2005032300) {
        $success = $success && modify_database('', 'ALTER TABLE prefix_quiz_question_version RENAME TO prefix_quiz_question_versions;');
    }
    if ($success && $oldversion < 2005041200) {
        // replace wiki-like with markdown
        include_once "{$CFG->dirroot}/lib/wiki_to_markdown.php";
        $wtm = new WikiToMarkdown();
        $sql = "select course from {$CFG->prefix}quiz_categories, {$CFG->prefix}quiz_questions ";
        $sql .= "where {$CFG->prefix}quiz_category.id = {$CFG->prefix}quiz_questions.category ";
        $sql .= "and {$CFG->prefix}quiz_questions.id = ";
        $wtm->update('quiz_questions', 'questiontext', 'questiontextformat', $sql);
    }
    if ($success && $oldversion < 2005041300) {
        $success = $success && modify_database('', "UPDATE prefix_quiz_questions SET hidden = '1' WHERE qtype ='" . RANDOM . "';");
    }
    if ($success && $oldversion < 2005042002) {
        $success = $success && table_column('quiz_answers', 'answer', 'answer', 'text', '', '', '', 'not null', '');
    }
    if ($success && $oldversion < 2005042400) {
        begin_sql();
        // Changes to quiz table
        // The bits of the optionflags field will hold various option flags
        $success = $success && table_column('quiz', '', 'optionflags', 'integer', '10', 'unsigned', '0', 'not null', 'timeclose');
        // The penalty scheme
        $success = $success && table_column('quiz', '', 'penaltyscheme', 'integer', '4', 'unsigned', '0', 'not null', 'optionflags');
        // The review options are now all stored in the bits of the review field
        $success = $success && table_column('quiz', 'review', 'review', 'integer', 10, 'unsigned', 0, 'not null', '');
        /// Changes to quiz_attempts table
        // The preview flag marks teacher previews
        $success = $success && table_column('quiz_attempts', '', 'preview', 'tinyint', '2', 'unsigned', '0', 'not null', 'timemodified');
        // The layout is the list of questions with inserted page breaks.
        $success = $success && table_column('quiz_attempts', '', 'layout', 'text', '', '', '', 'not null', 'timemodified');
        // For old quiz attempts we will set this to the repaginated question list from $quiz->questions
        /// The following updates of field values require a loop through all quizzes
        // This is because earlier versions of mysql don't allow joins in UPDATE
        if ($quizzes = get_records('quiz')) {
            // turn reporting off temporarily to avoid one line output per set_field
            $olddebug = $db->debug;
            $db->debug = false;
            foreach ($quizzes as $quiz) {
                // repaginate
                $quiz->questions = $quiz->questionsperpage ? quiz_repaginate($quiz->questions, $quiz->questionsperpage) : $quiz->questions;
                if ($quiz->questionsperpage) {
                    $quiz->questions = quiz_repaginate($quiz->questions, $quiz->questionsperpage);
                    $success = $success && set_field('quiz', 'questions', $quiz->questions, 'id', $quiz->id);
                }
                set_field('quiz_attempts', 'layout', $quiz->questions, 'quiz', $quiz->id);
                // set preview flag
                if ($teachers = get_course_teachers($quiz->course)) {
                    $teacherids = implode(',', array_keys($teachers));
                    $success = $success && execute_sql("UPDATE {$CFG->prefix}quiz_attempts SET preview = 1 WHERE userid IN ({$teacherids})");
                }
                // set review flags in quiz table
                $review = QUIZ_REVIEW_IMMEDIATELY & QUIZ_REVIEW_RESPONSES + QUIZ_REVIEW_SCORES;
                if ($quiz->feedback) {
                    $review += QUIZ_REVIEW_IMMEDIATELY & QUIZ_REVIEW_FEEDBACK;
                }
                if ($quiz->correctanswers) {
                    $review += QUIZ_REVIEW_IMMEDIATELY & QUIZ_REVIEW_ANSWERS;
                }
                if ($quiz->review & 1) {
                    $review += QUIZ_REVIEW_CLOSED;
                }
                if ($quiz->review & 2) {
                    $review += QUIZ_REVIEW_OPEN;
                }
                $success = $success && set_field('quiz', 'review', $review, 'id', $quiz->id);
            }
            $db->debug = $olddebug;
        }
        // We can now drop the fields whose data has been moved to the review field
        $success = $success && execute_sql(" ALTER TABLE {$CFG->prefix}quiz DROP COLUMN feedback");
        $success = $success && execute_sql(" ALTER TABLE {$CFG->prefix}quiz DROP COLUMN correctanswers");
        /// Renaming tables
        // rename the quiz_question_grades table to quiz_question_instances
        $success = $success && modify_database('', 'ALTER TABLE prefix_quiz_question_grades RENAME TO prefix_quiz_question_instances;');
        $success = $success && modify_database('', 'ALTER TABLE prefix_quiz_question_grades_id_seq RENAME TO prefix_quiz_question_instances_id_seq;');
        $success = $success && modify_database('', 'ALTER TABLE prefix_quiz_question_instances ALTER COLUMN id SET DEFAULT nextval(\'prefix_quiz_question_instances_id_seq\');');
        $success = $success && modify_database('', 'DROP INDEX prefix_quiz_question_grades_quiz_idx');
        $success = $success && modify_database('', 'DROP INDEX prefix_quiz_question_grades_question_idx;');
        $success = $success && modify_database('', 'CREATE INDEX prefix_quiz_question_instances_quiz_idx ON prefix_quiz_question_instances (quiz);');
        $success = $success && modify_database('', 'CREATE INDEX prefix_quiz_question_instances_question_idx ON prefix_quiz_question_instances (question);');
        // rename the quiz_responses table quiz_states
        $success = $success && modify_database('', 'ALTER TABLE prefix_quiz_responses RENAME TO prefix_quiz_states;');
        $success = $success && modify_database('', 'ALTER TABLE prefix_quiz_responses_id_seq RENAME TO prefix_quiz_states_id_seq;');
        $success = $success && modify_database('', 'ALTER TABLE prefix_quiz_states ALTER COLUMN id SET DEFAULT nextval(\'prefix_quiz_states_id_seq\');');
        $success = $success && modify_database('', 'DROP INDEX prefix_quiz_responses_attempt_idx;');
        $success = $success && modify_database('', 'DROP INDEX prefix_quiz_responses_question_idx;');
        $success = $success && modify_database('', 'CREATE INDEX prefix_quiz_states_attempt_idx ON prefix_quiz_states (attempt);');
        $success = $success && modify_database('', 'CREATE INDEX prefix_quiz_states_question_idx ON prefix_quiz_states (question);');
        /// add columns to quiz_states table
        // The sequence number of the state.
        $success = $success && table_column('quiz_states', '', 'seq_number', 'integer', '6', 'unsigned', '0', 'not null', 'originalquestion');
        // For existing states we leave this at 0 because in the old quiz code there was only one response allowed
        // The time the state was created.
        $success = $success && table_column('quiz_states', '', 'timestamp', 'integer', '10', 'unsigned', '0', 'not null', 'answer');
        // For existing states we will below set this to the timemodified field of the attempt
        // The type of event that led to the creation of the state
        $success = $success && table_column('quiz_states', '', 'event', 'integer', '4', 'unsigned', '0', 'not null', 'timestamp');
        // The raw grade
        $success = $success && table_column('quiz_states', '', 'raw_grade', 'varchar', '10', '', '', 'not null', 'grade');
        // For existing states (no penalties) this is equal to the grade
        $success = $success && execute_sql("UPDATE {$CFG->prefix}quiz_states SET raw_grade = grade");
        // The penalty that the response attracted
        $success = $success && table_column('quiz_states', '', 'penalty', 'varchar', '10', '', '0.0', 'not null', 'raw_grade');
        // For existing states this can stay at 0 because penalties did not exist previously.
        /// New table for pointers to newest and newest graded states
        $success = $success && modify_database('', "CREATE TABLE prefix_quiz_newest_states (\n                               id SERIAL PRIMARY KEY,\n                               attemptid integer NOT NULL default '0',\n                               questionid integer NOT NULL default '0',\n                               newest integer NOT NULL default '0',\n                               newgraded integer NOT NULL default '0',\n                               sumpenalty varchar(10) NOT NULL default '0.0'\n                             );");
        $success = $success && modify_database('CREATE UNIQUE INDEX prefix_quiz_newest_states_attempt_idx ON prefix_quiz_newest_states (attemptid,questionid);');
        /// Now upgrade some fields in states and newest_states tables where necessary
        // to save time on large sites only do this for attempts that have not yet been finished.
        if ($attempts = get_records_select('quiz_attempts', 'timefinish = 0')) {
            // turn reporting off temporarily to avoid one line output per set_field
            $olddebug = $db->debug;
            $db->debug = false;
            foreach ($attempts as $attempt) {
                quiz_upgrade_states($attempt);
            }
            $db->debug = $olddebug;
        }
        /// Entries for the log_display table
        $success = $success && modify_database('', " INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('quiz', 'preview', 'quiz', 'name');");
        $success = $success && modify_database('', " INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('quiz', 'start attempt', 'quiz', 'name');");
        $success = $success && modify_database('', " INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('quiz', 'close attempt', 'quiz', 'name');");
        /// update the default settings in $CFG
        $review = QUIZ_REVIEW_IMMEDIATELY & QUIZ_REVIEW_RESPONSES + QUIZ_REVIEW_SCORES;
        if (!empty($CFG->quiz_feedback)) {
            $review += QUIZ_REVIEW_IMMEDIATELY & QUIZ_REVIEW_FEEDBACK;
        }
        if (!empty($CFG->quiz_correctanswers)) {
            $review += QUIZ_REVIEW_IMMEDIATELY & QUIZ_REVIEW_ANSWERS;
        }
        if (isset($CFG->quiz_review) and $CFG->quiz_review & 1) {
            $review += QUIZ_REVIEW_CLOSED;
        }
        if (isset($CFG->quiz_review) and $CFG->quiz_review & 2) {
            $review += QUIZ_REVIEW_OPEN;
        }
        $success = $success && set_config('quiz_review', $review);
        /// Use tolerance instead of min and max in numerical question type
        $success = $success && table_column('quiz_numerical', '', 'tolerance', 'varchar', '255', '', '0.0', 'not null', 'question');
        $success = $success && execute_sql("UPDATE {$CFG->prefix}quiz_numerical SET tolerance = (max::text::real-min::text::real)/2");
        $success = $success && modify_database('', 'ALTER TABLE prefix_quiz_numerical DROP COLUMN min');
        // Replaced by tolerance
        $success = $success && modify_database('', 'ALTER TABLE prefix_quiz_numerical DROP COLUMN max');
        // Replaced by tolerance
        /// Tables for Remote Questions
        $success = $success && modify_database('', "CREATE TABLE prefix_quiz_rqp (\n                                 id SERIAL PRIMARY KEY,\n                                 question integer NOT NULL default '0',\n                                 type integer NOT NULL default '0',\n                                 source text NOT NULL,\n                                 format varchar(255) NOT NULL default '',\n                                 flags integer NOT NULL default '0',\n                                 maxscore integer NOT NULL default '1'\n                               );");
        $success = $success && modify_database('', "CREATE INDEX prefix_quiz_rqp_question_idx ON prefix_quiz_rqp (question);");
        $success = $success && modify_database('', "CREATE TABLE prefix_quiz_rqp_states (\n                                 id SERIAL PRIMARY KEY,\n                                 stateid integer NOT NULL default '0',\n                                 responses text NOT NULL,\n                                 persistent_data text NOT NULL,\n                                 template_vars text NOT NULL\n                               );");
        $success = $success && modify_database('', "CREATE TABLE prefix_quiz_rqp_types (\n                                id SERIAL PRIMARY KEY,\n                                name varchar(255) NOT NULL default '',\n                                rendering_server varchar(255) NOT NULL default '',\n                                cloning_server varchar(255) NOT NULL default '',\n                                flags integer NOT NULL default '0'\n                              );");
        $success = $success && modify_database('', "CREATE UNIQUE INDEX prefix_quiz_rqp_types_name_uk ON prefix_quiz_rqp_types (name);");
        if ($success) {
            $success = $success && commit_sql();
        } else {
            rollback_sql();
        }
    }
    if ($success && $oldversion < 2005042900 && false) {
        // We don't want this to be executed any more!!!
        begin_sql();
        $success = $success && table_column('quiz_multianswers', '', 'sequence', 'varchar', '255', '', '', 'not null', 'question');
        $success = $success && table_column('quiz_numerical', '', 'answers', 'varchar', '255', '', '', 'not null', 'answer');
        $success = $success && modify_database('', 'UPDATE prefix_quiz_numerical SET answers = answer');
        $success = $success && table_column('quiz_questions', '', 'parent', 'integer', '10', 'unsigned', '0', 'not null', 'category');
        $success = $success && modify_database('', "UPDATE prefix_quiz_questions SET parent = id WHERE qtype ='" . RANDOM . "';");
        // convert multianswer questions to the new model
        if ($multianswers = get_records_sql("SELECT m.id, q.category, q.id AS parent,\n                                        q.name, q.questiontextformat, m.norm AS\n                                        defaultgrade, m.answertype AS qtype,\n                                        q.version, q.hidden, m.answers,\n                                        m.positionkey\n                                        FROM {$CFG->prefix}quiz_questions q,\n                                             {$CFG->prefix}quiz_multianswers m\n                                        WHERE q.qtype = '" . MULTIANSWER . "'\n                                        AND   q.id = m.question\n                                        ORDER BY q.id ASC, m.positionkey ASC")) {
            $multianswers = array_values($multianswers);
            $n = count($multianswers);
            $parent = $multianswers[0]->parent;
            $sequence = array();
            // turn reporting off temporarily to avoid one line output per set_field
            $olddebug = $db->debug;
            $db->debug = false;
            for ($i = 0; $i < $n; $i++) {
                $answers = $multianswers[$i]->answers;
                unset($multianswers[$i]->answers);
                $pos = $multianswers[$i]->positionkey;
                unset($multianswers[$i]->positionkey);
                // create questions for all the multianswer victims
                unset($multianswers[$i]->id);
                $multianswers[$i]->length = 0;
                $multianswers[$i]->questiontext = '';
                $multianswers[$i]->stamp = make_unique_id_code();
                $id = insert_record('quiz_questions', $multianswers[$i]);
                $success = $success && $id;
                $sequence[$pos] = $id;
                // update the answers table to point to these new questions
                $success = $success && modify_database('', "UPDATE prefix_quiz_answers SET question = '{$id}' WHERE id IN ({$answers});");
                // update the questiontype tables to point to these new questions
                if (SHORTANSWER == $multianswers[$i]->qtype) {
                    $success = $success && modify_database('', "UPDATE prefix_quiz_shortanswer SET question = '{$id}' WHERE answers = '{$answers}';");
                } else {
                    if (NUMERICAL == $multianswers[$i]->qtype) {
                        if (strpos($answers, ',')) {
                            $numerical = get_records_list('quiz_numerical', 'answer', $answers);
                            // Get the biggest tolerance value
                            $tolerance = 0;
                            foreach ($numerical as $num) {
                                $tolerance = $tolerance < $num->tolerance ? $num->tolerance : $tolerance;
                            }
                            $success = $success && delete_records_select('quiz_numerical', "answer IN ({$answers})");
                            $new = new stdClass();
                            $new->question = $id;
                            $new->tolerance = $tolerance;
                            $new->answers = $answers;
                            $success = $success && insert_record('quiz_numerical', $new);
                            unset($numerical, $new, $tolerance);
                        } else {
                            $success = $success && modify_database('', "UPDATE prefix_quiz_numerical SET question = '{$id}', answers = '{$answers}' WHERE answer IN ({$answers});");
                        }
                    } else {
                        if (MULTICHOICE == $multianswers[$i]->qtype) {
                            $success = $success && modify_database('', "UPDATE prefix_quiz_multichoice SET question = '{$id}' WHERE answers = '{$answers}';");
                        }
                    }
                }
                if (!isset($multianswers[$i + 1]) || $parent != $multianswers[$i + 1]->parent) {
                    $success = $success && delete_records('quiz_multianswers', 'question', $parent);
                    $multi = new stdClass();
                    $multi->question = $parent;
                    $multi->sequence = implode(',', $sequence);
                    $success = $success && insert_record('quiz_multianswers', $multi);
                    if (isset($multianswers[$i + 1])) {
                        $parent = $multianswers[$i + 1]->parent;
                        $sequence = array();
                    }
                }
            }
            $db->debug = $olddebug;
        }
        // Remove redundant fields from quiz_multianswers
        $success = $success && modify_database('', 'ALTER TABLE prefix_quiz_multianswers DROP COLUMN answers');
        $success = $success && modify_database('', 'ALTER TABLE prefix_quiz_multianswers DROP COLUMN positionkey');
        $success = $success && modify_database('', 'ALTER TABLE prefix_quiz_multianswers DROP COLUMN answertype');
        $success = $success && modify_database('', 'ALTER TABLE prefix_quiz_multianswers DROP COLUMN norm');
        // Change numerical from answer to answers
        $success = $success && modify_database('', 'ALTER TABLE prefix_quiz_numerical DROP COLUMN answer');
        if ($success) {
            $success = $success && commit_sql();
        } else {
            rollback_sql();
        }
    }
    if ($success && $oldversion < 2005050300) {
        // length of question determines question numbering. Currently all questions require one
        // question number except for DESCRIPTION questions.
        $success = $success && table_column('quiz_questions', '', 'length', 'integer', '10', 'unsigned', '1', 'not null', 'qtype');
        $success = $success && execute_sql("UPDATE {$CFG->prefix}quiz_questions SET length = 0 WHERE qtype = '7'");
    }
    if ($success && $oldversion < 2005050408) {
        $success = $success && table_column('quiz_questions', '', 'penalty', 'float', '', '', '0.1', 'not null', 'defaultgrade');
    }
    if ($success && $oldversion < 2005051401) {
        // Some earlier changes are undone here, so we need another condition
        if ($oldversion >= 2005042900) {
            // Restore the answer field
            $success = $success && table_column('quiz_numerical', '', 'answer', 'integer', '10', 'unsigned', '0', 'not null', 'answers');
            $singleanswer = array();
            if ($numericals = get_records('quiz_numerical')) {
                $numericals = array_values($numericals);
                $n = count($numericals);
                for ($i = 0; $i < $n; $i++) {
                    $numerical =& $numericals[$i];
                    if (strpos($numerical->answers, ',')) {
                        // comma separated list?
                        // Back this up to delete the record after the new ones are created
                        $id = $numerical->id;
                        unset($numerical->id);
                        // We need to create a record for each answer id
                        $answers = explode(',', $numerical->answers);
                        foreach ($answers as $answer) {
                            $numerical->answer = $answer;
                            $success = $success && insert_record('quiz_numerical', $numerical);
                        }
                        // ... and get rid of the old record
                        $success = $success && delete_records('quiz_numerical', 'id', $id);
                    } else {
                        $singleanswer[] = $numerical->id;
                    }
                }
            }
            // Do all of these at once
            if (!empty($singleanswer)) {
                $singleanswer = implode(',', $singleanswer);
                $success = $success && modify_database('', "UPDATE prefix_quiz_numerical SET answer = answers WHERE id IN ({$singleanswer});");
            }
            // All answer fields are set, so we can delete the answers field
            $success = $success && modify_database('', 'ALTER TABLE prefix_quiz_numerical DROP answers');
            // If the earlier changes weren't made we can safely do only the
            // bits here.
        } else {
            // Comma separated questionids will be stored as sequence
            $success = $success && table_column('quiz_multianswers', '', 'sequence', 'varchar', '255', '', '', 'not null', 'question');
            // Change the type of positionkey to int, so that the sorting works!
            $success = $success && table_column('quiz_multianswers', 'positionkey', 'positionkey', 'integer', '10', 'unsigned', '0', 'not null', '');
            $success = $success && table_column('quiz_questions', '', 'parent', 'integer', '10', 'unsigned', '0', 'not null', 'category');
            $success = $success && modify_database('', "UPDATE prefix_quiz_questions SET parent = id WHERE qtype ='" . RANDOM . "';");
            // Each multianswer record is converted to a question object and then
            // inserted as a new question into the quiz_questions table.
            // After that the question fields in the quiz_answers table and the
            // qtype specific tables are updated to point to the new question id.
            // Note: The quiz_numerical table is different as it stores one record
            //       per defined answer (to allow different tolerance values for
            //       different possible answers. (Currently multiple answers are
            //       not supported by the numerical editing interface, but all
            //       all processing code does support that possibility.
            if ($multianswers = get_records_sql("SELECT m.id, q.category, " . "q.id AS parent, " . "q.name, q.questiontextformat, " . "m.norm AS defaultgrade, " . "m.answertype AS qtype, " . "q.version, q.hidden, m.answers, " . "m.positionkey " . "FROM {$CFG->prefix}quiz_questions q, " . "     {$CFG->prefix}quiz_multianswers m " . "WHERE q.qtype = '" . MULTIANSWER . "' " . "AND   q.id = m.question " . "ORDER BY q.id ASC, m.positionkey ASC")) {
                // ordered by positionkey
                $multianswers = array_values($multianswers);
                $n = count($multianswers);
                $parent = $multianswers[0]->parent;
                $sequence = array();
                $positions = array();
                // Turn reporting off temporarily to avoid one line output per set_field
                global $db;
                $olddebug = $db->debug;
                // $db->debug = false;
                for ($i = 0; $i < $n; $i++) {
                    // Backup these two values before unsetting the object fields
                    $answers = $multianswers[$i]->answers;
                    unset($multianswers[$i]->answers);
                    $pos = $multianswers[$i]->positionkey;
                    unset($multianswers[$i]->positionkey);
                    // Needed for substituting multianswer ids with position keys in the $state->answer field
                    $positions[$multianswers[$i]->id] = $pos;
                    // Create questions for all the multianswer victims
                    unset($multianswers[$i]->id);
                    $multianswers[$i]->length = 0;
                    $multianswers[$i]->questiontext = '';
                    $multianswers[$i]->stamp = make_unique_id_code();
                    // $multianswers[$i]->parent is set in the query
                    // $multianswers[$i]->defaultgrade is set in the query
                    // $multianswers[$i]->qtype is set in the query
                    $id = insert_record('quiz_questions', $multianswers[$i]);
                    $success = $success && $id;
                    $sequence[$pos] = $id;
                    // Update the quiz_answers table to point to these new questions
                    $success = $success && modify_database('', "UPDATE prefix_quiz_answers SET question = '{$id}' WHERE id IN ({$answers});");
                    // Update the questiontype tables to point to these new questions
                    if (SHORTANSWER == $multianswers[$i]->qtype) {
                        $success = $success && modify_database('', "UPDATE prefix_quiz_shortanswer SET question = '{$id}' WHERE answers = '{$answers}';");
                    } else {
                        if (MULTICHOICE == $multianswers[$i]->qtype) {
                            $success = $success && modify_database('', "UPDATE prefix_quiz_multichoice SET question = '{$id}' WHERE answers = '{$answers}';");
                        } else {
                            if (NUMERICAL == $multianswers[$i]->qtype) {
                                $success = $success && modify_database('', "UPDATE prefix_quiz_numerical SET question = '{$id}' WHERE answer IN ({$answers});");
                            }
                        }
                    }
                    // Whenever we're through with the subquestions of one multianswer
                    // question we delete the old records in the multianswers table,
                    // store a new record with the sequence in the multianswers table
                    // and point $parent to the next multianswer question.
                    if (!isset($multianswers[$i + 1]) || $parent != $multianswers[$i + 1]->parent) {
                        // Substituting multianswer ids with position keys in the $state->answer field
                        if ($states = get_records('quiz_states', 'question', $parent)) {
                            foreach ($states as $state) {
                                $reg = array();
                                preg_match_all('/(?:^|,)([0-9]+)-([^,]*)/', $state->answer, $reg);
                                $state->answer = '';
                                $m = count($reg[1]);
                                for ($j = 0; $j < $m; $j++) {
                                    if (isset($positions[$reg[1][$j]])) {
                                        $state->answer .= $positions[$reg[1][$j]] . '-' . $reg[2][$j] . ',';
                                    } else {
                                        notify("Undefined multianswer id ({$reg[1][$j]}) used in state #{$state->id}!");
                                        $state->answer .= $j + 1 . '-' . $reg[2][$j] . ',';
                                    }
                                }
                                $state->answer = rtrim($state->answer, ',');
                                // strip trailing comma
                                $success = $success && update_record('quiz_states', $state);
                            }
                        }
                        $success = $success && delete_records('quiz_multianswers', 'question', $parent);
                        $multi = new stdClass();
                        $multi->question = $parent;
                        $multi->sequence = implode(',', $sequence);
                        $success = $success && insert_record('quiz_multianswers', $multi);
                        if (isset($multianswers[$i + 1])) {
                            $parent = $multianswers[$i + 1]->parent;
                            $sequence = array();
                            $positions = array();
                        }
                    }
                }
                $db->debug = $olddebug;
            }
            // Remove redundant fields from quiz_multianswers
            $success = $success && modify_database('', 'ALTER TABLE prefix_quiz_multianswers DROP answers');
            $success = $success && modify_database('', 'ALTER TABLE prefix_quiz_multianswers DROP positionkey');
            $success = $success && modify_database('', 'ALTER TABLE prefix_quiz_multianswers DROP answertype');
            $success = $success && modify_database('', 'ALTER TABLE prefix_quiz_multianswers DROP norm');
        }
    }
    if ($success && $oldversion < 2005051402) {
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_attemptonlast_datasets DROP CONSTRAINT category;", false);
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_attemptonlast_datasets DROP CONSTRAINT {$CFG->prefix}attemptonlast_datasets_category_userid;", false);
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_attemptonlast_datasets DROP CONSTRAINT {$CFG->prefix}quiz_category_userid_unique;", false);
        $success = $success && modify_database('', 'ALTER TABLE prefix_quiz_attemptonlast_datasets ADD CONSTRAINT prefix_quiz_category_userid_unique UNIQUE (category,userid);');
    }
    if ($success && $oldversion < 2005060300) {
        // We need to remove some duplicate entries that may be present in some databases
        // due to a faulty restore script
        // Remove duplicate entries from quiz_numerical
        if ($dups = get_records_sql("\n                SELECT question, answer, count(*) as num\n                FROM {$CFG->prefix}quiz_numerical\n                GROUP BY question, answer\n                HAVING count(*) > 1")) {
            foreach ($dups as $dup) {
                $ids = get_records_sql("\n                    SELECT id, id\n                    FROM {$CFG->prefix}quiz_numerical\n                    WHERE question = '{$dup->question}'\n                    AND answer = '{$dup->answer}'");
                $skip = true;
                foreach ($ids as $id) {
                    if ($skip) {
                        $skip = false;
                    } else {
                        $success = $success && delete_records('quiz_numerical', 'id', $id->id);
                    }
                }
            }
        }
        // Remove duplicate entries from quiz_shortanswer
        if ($dups = get_records_sql("\n                SELECT question, answers, count(*) as num\n                FROM {$CFG->prefix}quiz_shortanswer\n                GROUP BY question, answers\n                HAVING count(*) > 1")) {
            foreach ($dups as $dup) {
                $ids = get_records_sql("\n                    SELECT id, id\n                    FROM {$CFG->prefix}quiz_shortanswer\n                    WHERE question = '{$dup->question}'\n                    AND answers = '{$dup->answers}'");
                $skip = true;
                foreach ($ids as $id) {
                    if ($skip) {
                        $skip = false;
                    } else {
                        $success = $success && delete_records('quiz_shortanswer', 'id', $id->id);
                    }
                }
            }
        }
        // Remove duplicate entries from quiz_multichoice
        if ($dups = get_records_sql("\n                SELECT question, answers, count(*) as num\n                FROM {$CFG->prefix}quiz_multichoice\n                GROUP BY question, answers\n                HAVING count(*) > 1")) {
            foreach ($dups as $dup) {
                $ids = get_records_sql("\n                    SELECT id, id\n                    FROM {$CFG->prefix}quiz_multichoice\n                    WHERE question = '{$dup->question}'\n                    AND answers = '{$dup->answers}'");
                $skip = true;
                foreach ($ids as $id) {
                    if ($skip) {
                        $skip = false;
                    } else {
                        $success = $success && delete_records('quiz_multichoice', 'id', $id->id);
                    }
                }
            }
        }
        //Search all the orphan categories (those whose course doesn't exist)
        //and process them, deleting or moving them to site course - Bug 2459
        //Set debug to false
        $olddebug = $db->debug;
        $db->debug = false;
        //Iterate over all the quiz_categories records to get their course id
        if ($courses = get_records_sql("SELECT DISTINCT course as id, course\n                                         FROM {$CFG->prefix}quiz_categories")) {
            //Iterate over courses
            foreach ($courses as $course) {
                //If the course doesn't exist, orphan category found!
                //Process it with question_delete_course(). It will do all the hard work.
                if (!record_exists('course', 'id', $course->id)) {
                    require_once "{$CFG->libdir}/questionlib.php";
                    $success = $success && question_delete_course($course);
                }
            }
        }
        //Reset rebug to its original state
        $db->debug = $olddebug;
    }
    if ($success && $oldversion < 2005060301) {
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_rqp_type RENAME TO ' . $CFG->prefix . 'quiz_rqp_types');
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_rqp_type_id_seq RENAME TO ' . $CFG->prefix . 'rqp_types_id_seq');
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_rqp_types ALTER COLUMN id SET DEFAULT nextval(\'' . $CFG->prefix . 'quiz_rqp_types_id_seq\')');
        $success = $success && execute_sql('DROP INDEX ' . $CFG->prefix . 'quiz_rqp_type_name_uk');
        $success = $success && execute_sql('CREATE UNIQUE INDEX ' . $CFG->prefix . 'quiz_rqp_types_name_uk ON ' . $CFG->prefix . 'quiz_rqp_types (name);');
    }
    if ($success && $oldversion < 2005060302) {
        // Mass cleanup of bad postgres upgrade scripts
        $success = $success && execute_sql('CREATE UNIQUE INDEX ' . $CFG->prefix . 'quiz_newest_states_attempt_idx ON ' . $CFG->prefix . 'quiz_newest_states (attemptid, questionid)', false);
        $success = $success && execute_sql('ALTER TABLE ONLY ' . $CFG->prefix . 'quiz_attemptonlast_datasets DROP CONSTRAINT ' . $CFG->prefix . 'quiz_category_userid_unique', false);
        $success = $success && execute_sql('ALTER TABLE ONLY ' . $CFG->prefix . 'quiz_attemptonlast_datasets ADD CONSTRAINT ' . $CFG->prefix . 'quiz_attemptonlast_datasets_category_userid UNIQUE (category, userid)', false);
        $success = $success && execute_sql('ALTER TABLE ONLY ' . $CFG->prefix . 'quiz_question_instances DROP CONSTRAINT ' . $CFG->prefix . 'quiz_question_grades_pkey', false);
        $success = $success && execute_sql('ALTER TABLE ONLY ' . $CFG->prefix . 'quiz_question_instances ADD CONSTRAINT ' . $CFG->prefix . 'quiz_question_instances_pkey PRIMARY KEY (id)', false);
        $success = $success && execute_sql('ALTER TABLE ONLY ' . $CFG->prefix . 'quiz_question_versions DROP CONSTRAINT ' . $CFG->prefix . 'quiz_question_version_pkey', false);
        $success = $success && execute_sql('ALTER TABLE ONLY ' . $CFG->prefix . 'quiz_question_versions ADD CONSTRAINT ' . $CFG->prefix . 'quiz_question_versions_pkey PRIMARY KEY (id)', false);
        $success = $success && execute_sql('ALTER TABLE ONLY ' . $CFG->prefix . 'quiz_states DROP CONSTRAINT ' . $CFG->prefix . 'quiz_responses_pkey', false);
        $success = $success && execute_sql('ALTER TABLE ONLY ' . $CFG->prefix . 'quiz_states ADD CONSTRAINT ' . $CFG->prefix . 'quiz_states_pkey PRIMARY KEY (id)', false);
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz ALTER decimalpoints SET NOT NULL', false);
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz ALTER optionflags SET NOT NULL', false);
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz ALTER penaltyscheme SET NOT NULL', false);
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz ALTER popup SET NOT NULL', false);
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz ALTER questionsperpage SET NOT NULL', false);
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz ALTER review SET NOT NULL', false);
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_answers ALTER answer SET NOT NULL', false);
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_attempts ALTER layout SET NOT NULL', false);
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_attempts ALTER preview SET NOT NULL', false);
        $success = $success && table_column('quiz_calculated', 'correctanswerformat', 'correctanswerformat', 'integer', '16', 'unsigned', '2');
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_categories ALTER parent SET NOT NULL', false);
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_categories ALTER sortorder SET NOT NULL', false);
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_grades ALTER grade SET NOT NULL', false);
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_multianswers ALTER sequence SET NOT NULL', false);
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_numerical ALTER tolerance SET NOT NULL', false);
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_questions ALTER hidden SET NOT NULL', false);
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_questions ALTER length SET NOT NULL', false);
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_questions ALTER parent SET NOT NULL', false);
        $success = $success && table_column('quiz_questions', 'penalty', 'penalty', 'real', '', 'UNSIGNED', '0.1');
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_states ALTER answer SET NOT NULL', false);
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_states ALTER event SET NOT NULL', false);
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_states ALTER originalquestion SET NOT NULL', false);
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_states ALTER penalty SET NOT NULL', false);
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_states ALTER raw_grade SET NOT NULL', false);
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_states ALTER seq_number SET NOT NULL', false);
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_states ALTER timestamp SET NOT NULL', false);
    }
    if ($success && $oldversion < 2005100500) {
        // clean up an old mistake. This mistake may not have been made, so don't worry about failures.
        $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_question_version_id_seq RENAME TO ' . $CFG->prefix . 'quiz_question_versions_id_seq', false);
        $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_question_versions ALTER COLUMN id SET DEFAULT nextval(\'' . $CFG->prefix . 'quiz_question_versions_id_seq\')', false);
    }
    if ($success && $oldversion < 2006020801) {
        $success = $success && table_column("quiz", "", "delay1", "INTEGER", "10", "UNSIGNED", "0", "NOT NULL", "popup");
        $success = $success && table_column("quiz", "", "delay2", "INTEGER", "10", "UNSIGNED", "0", "NOT NULL", "delay1");
    }
    if ($success && $oldversion < 2006021101) {
        // set defaultgrade field properly (probably not necessary, but better make sure)
        $success && execute_sql("UPDATE {$CFG->prefix}quiz_questions SET defaultgrade = '1' WHERE defaultgrade = '0'", false);
        $success && execute_sql("UPDATE {$CFG->prefix}quiz_questions SET defaultgrade = '0' WHERE qtype = '7'", false);
    }
    if ($success && $oldversion < 2006021103) {
        // add new field to store the question-level shuffleanswers option
        $success = $success && table_column('quiz_match', '', 'shuffleanswers', 'tinyint', '4', 'unsigned', '1', 'not null', 'subquestions');
        $success = $success && table_column('quiz_multichoice', '', 'shuffleanswers', 'tinyint', '4', 'unsigned', '1', 'not null', 'single');
        $success = $success && table_column('quiz_randomsamatch', '', 'shuffleanswers', 'tinyint', '4', 'unsigned', '1', 'not null', 'choose');
    }
    if ($success && $oldversion < 2006021104) {
        // add originalversion field for the new versioning mechanism
        $success = $success && table_column('quiz_question_versions', '', 'originalquestion', 'int', '10', 'unsigned', '0', 'not null', 'newquestion');
    }
    if ($success && $oldversion < 2006021302) {
        $success = $success && table_column('quiz_match_sub', '', 'code', 'int', '10', 'unsigned', '0', 'not null', 'id');
        $success = $success && execute_sql("UPDATE {$CFG->prefix}quiz_match_sub SET code = id", false);
    }
    if ($success && $oldversion < 2006021304) {
        // convert sequence field to text to accomodate very long sequences, see bug 4257
        $success = $success && table_column('quiz_multianswers', 'sequence', 'sequence', 'text', '', '', '', 'not null', 'question');
    }
    if ($success && $oldversion < 2006021400) {
        // modify_database('','CREATE UNIQUE INDEX prefix_quiz_attempts_uniqueid_uk ON prefix_quiz_attempts (uniqueid);');
        // this index will not be created since uniqueid was not added, proper upgrade will be on 2006042801
    }
    if ($success && $oldversion < 2006021501) {
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_newest_states RENAME TO {$CFG->prefix}question_sessions", false);
    }
    if ($success && $oldversion < 2006021900) {
        $success = $success && modify_database('', "\n            CREATE TABLE prefix_quiz_essay (\n                id SERIAL PRIMARY KEY,\n                question integer NOT NULL default '0',\n                answer varchar(255) NOT NULL default ''\n            ) ");
        $success = $success && modify_database('', "\n            CREATE TABLE prefix_quiz_essay_states (\n                id SERIAL PRIMARY KEY,\n                stateid integer NOT NULL default '0',\n                graded integer NOT NULL default '0',\n                fraction varchar(10) NOT NULL default '0.0',\n                response text NOT NULL default ''\n            );");
        // convert grade fields to real
        $success = $success && table_column('quiz_attempts', 'sumgrades', 'sumgrades', 'real', '', '', '0', 'not null');
        $success = $success && table_column('quiz_answers', 'fraction', 'fraction', 'real', '', '', '0', 'not null');
        $success = $success && table_column('quiz_essay_states', 'fraction', 'fraction', 'real', '', '', '0', 'not null');
        $success = $success && set_field('quiz_states', 'grade', 0, 'grade', '');
        // Some values may be wrong, which caused errors in the following table_column calls.
        $success = $success && set_field('quiz_states', 'raw_grade', 0, 'raw_grade', '');
        $success = $success && set_field('quiz_states', 'penalty', 0, 'penalty', '');
        $success = $success && table_column('quiz_states', 'grade', 'grade', 'real', '', '', '0', 'not null');
        $success = $success && table_column('quiz_states', 'raw_grade', 'raw_grade', 'real', '', '', '0', 'not null');
        $success = $success && table_column('quiz_states', 'penalty', 'penalty', 'real', '', '', '0', 'not null');
        $success = $success && table_column('question_sessions', 'sumpenalty', 'sumpenalty', 'real', '', '', '0', 'not null');
    }
    if ($success && $oldversion < 2006030100) {
        // Fix up another table rename :(
        // THIS caused the mistake: execute_sql("ALTER TABLE {$CFG->prefix}quiz_newest_states RENAME TO {$CFG->prefix}question_sessions", false);
        $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_newest_states_id_seq RENAME TO ' . $CFG->prefix . 'question_sessions_id_seq', false);
        $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'question_sessions ALTER COLUMN id SET DEFAULT nextval(\'' . $CFG->prefix . 'question_sessions_id_seq\')', false);
    }
    if ($success && $oldversion < 2006030101) {
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_questions RENAME TO {$CFG->prefix}question");
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_questions_id_seq RENAME TO ' . $CFG->prefix . 'question_id_seq');
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'question ALTER COLUMN id SET DEFAULT nextval(\'' . $CFG->prefix . 'question_id_seq\')');
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_states RENAME TO {$CFG->prefix}question_states");
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_states_id_seq RENAME TO ' . $CFG->prefix . 'question_states_id_seq');
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'question_states ALTER COLUMN id SET DEFAULT nextval(\'' . $CFG->prefix . 'question_states_id_seq\')');
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_answers RENAME TO {$CFG->prefix}question_answers");
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_answers_id_seq RENAME TO ' . $CFG->prefix . 'question_answers_id_seq');
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'question_answers ALTER COLUMN id SET DEFAULT nextval(\'' . $CFG->prefix . 'question_answers_id_seq\')');
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_categories RENAME TO {$CFG->prefix}question_categories");
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_categories_id_seq RENAME TO ' . $CFG->prefix . 'question_categories_id_seq');
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'question_categories ALTER COLUMN id SET DEFAULT nextval(\'' . $CFG->prefix . 'question_categories_id_seq\')');
    }
    if ($success && $oldversion < 2006031202) {
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_truefalse RENAME TO {$CFG->prefix}question_truefalse");
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_truefalse_id_seq RENAME TO ' . $CFG->prefix . 'question_truefalse_id_seq');
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'question_truefalse ALTER COLUMN id SET DEFAULT nextval(\'' . $CFG->prefix . 'question_truefalse_id_seq\')');
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_shortanswer RENAME TO {$CFG->prefix}question_shortanswer");
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_shortanswer_id_seq RENAME TO ' . $CFG->prefix . 'question_shortanswer_id_seq');
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'question_shortanswer ALTER COLUMN id SET DEFAULT nextval(\'' . $CFG->prefix . 'question_shortanswer_id_seq\')');
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_multianswers RENAME TO {$CFG->prefix}question_multianswer");
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_multianswers_id_seq RENAME TO ' . $CFG->prefix . 'question_multianswer_id_seq');
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'question_multianswer ALTER COLUMN id SET DEFAULT nextval(\'' . $CFG->prefix . 'question_multianswer_id_seq\')');
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_multichoice RENAME TO {$CFG->prefix}question_multichoice");
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_multichoice_id_seq RENAME TO ' . $CFG->prefix . 'question_multichoice_id_seq');
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'question_multichoice ALTER COLUMN id SET DEFAULT nextval(\'' . $CFG->prefix . 'question_multichoice_id_seq\')');
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_numerical RENAME TO {$CFG->prefix}question_numerical");
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_numerical_id_seq RENAME TO ' . $CFG->prefix . 'question_numerical_id_seq');
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'question_numerical ALTER COLUMN id SET DEFAULT nextval(\'' . $CFG->prefix . 'question_numerical_id_seq\')');
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_numerical_units RENAME TO {$CFG->prefix}question_numerical_units");
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_numerical_units_id_seq RENAME TO ' . $CFG->prefix . 'question_numerical_units_id_seq');
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'question_numerical_units ALTER COLUMN id SET DEFAULT nextval(\'' . $CFG->prefix . 'question_numerical_units_id_seq\')');
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_randomsamatch RENAME TO {$CFG->prefix}question_randomsamatch");
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_randomsamatch_id_seq RENAME TO ' . $CFG->prefix . 'question_randomsamatch_id_seq');
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'question_randomsamatch ALTER COLUMN id SET DEFAULT nextval(\'' . $CFG->prefix . 'question_randomsamatch_id_seq\')');
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_match RENAME TO {$CFG->prefix}question_match");
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_match_id_seq RENAME TO ' . $CFG->prefix . 'question_match_id_seq');
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'question_match ALTER COLUMN id SET DEFAULT nextval(\'' . $CFG->prefix . 'question_match_id_seq\')');
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_match_sub RENAME TO {$CFG->prefix}question_match_sub");
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_match_sub_id_seq RENAME TO ' . $CFG->prefix . 'question_match_sub_id_seq');
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'question_match_sub ALTER COLUMN id SET DEFAULT nextval(\'' . $CFG->prefix . 'question_match_sub_id_seq\')');
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_calculated RENAME TO {$CFG->prefix}question_calculated");
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_calculated_id_seq RENAME TO ' . $CFG->prefix . 'question_calculated_id_seq');
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'question_calculated ALTER COLUMN id SET DEFAULT nextval(\'' . $CFG->prefix . 'question_calculated_id_seq\')');
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_dataset_definitions RENAME TO {$CFG->prefix}question_dataset_definitions");
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_dataset_definitions_id_seq RENAME TO ' . $CFG->prefix . 'question_dataset_definitions_id_seq');
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'question_dataset_definitions ALTER COLUMN id SET DEFAULT nextval(\'' . $CFG->prefix . 'question_dataset_definitions_id_seq\')');
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_dataset_items RENAME TO {$CFG->prefix}question_dataset_items");
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_dataset_items_id_seq RENAME TO ' . $CFG->prefix . 'question_dataset_items_id_seq');
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'question_dataset_items ALTER COLUMN id SET DEFAULT nextval(\'' . $CFG->prefix . 'question_dataset_items_id_seq\')');
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_question_datasets RENAME TO {$CFG->prefix}question_datasets");
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_question_datasets_id_seq RENAME TO ' . $CFG->prefix . 'question_datasets_id_seq');
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'question_datasets ALTER COLUMN id SET DEFAULT nextval(\'' . $CFG->prefix . 'question_datasets_id_seq\')');
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_rqp RENAME TO {$CFG->prefix}question_rqp");
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_rqp_id_seq RENAME TO ' . $CFG->prefix . 'question_rqp_id_seq');
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'question_rqp ALTER COLUMN id SET DEFAULT nextval(\'' . $CFG->prefix . 'question_rqp_id_seq\')');
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_rqp_states RENAME TO {$CFG->prefix}question_rqp_states");
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_rqp_states_id_seq RENAME TO ' . $CFG->prefix . 'question_rqp_states_id_seq');
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'question_rqp_states ALTER COLUMN id SET DEFAULT nextval(\'' . $CFG->prefix . 'question_rqp_states_id_seq\')');
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_rqp_types RENAME TO {$CFG->prefix}question_rqp_types");
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_rqp_types_id_seq RENAME TO ' . $CFG->prefix . 'question_rqp_types_id_seq');
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'question_rqp_types ALTER COLUMN id SET DEFAULT nextval(\'' . $CFG->prefix . 'question_rqp_types_id_seq\')');
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_essay RENAME TO {$CFG->prefix}question_essay");
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_essay_id_seq RENAME TO ' . $CFG->prefix . 'question_essay_id_seq');
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'question_essay ALTER COLUMN id SET DEFAULT nextval(\'' . $CFG->prefix . 'question_essay_id_seq\')');
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_essay_states RENAME TO {$CFG->prefix}question_essay_states");
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_essay_states_id_seq RENAME TO ' . $CFG->prefix . 'question_essay_states_id_seq');
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'question_essay_states ALTER COLUMN id SET DEFAULT nextval(\'' . $CFG->prefix . 'question_essay_states_id_seq\')');
    }
    if ($success && $oldversion < 2006032100) {
        // change from the old questiontype numbers to using the questiontype names
        $success = $success && table_column('question', 'qtype', 'qtype', 'varchar', 20, '', '', 'not null');
        $success = $success && set_field('question', 'qtype', 'shortanswer', 'qtype', 1);
        $success = $success && set_field('question', 'qtype', 'truefalse', 'qtype', 2);
        $success = $success && set_field('question', 'qtype', 'multichoice', 'qtype', 3);
        $success = $success && set_field('question', 'qtype', 'random', 'qtype', 4);
        $success = $success && set_field('question', 'qtype', 'match', 'qtype', 5);
        $success = $success && set_field('question', 'qtype', 'randomsamatch', 'qtype', 6);
        $success = $success && set_field('question', 'qtype', 'description', 'qtype', 7);
        $success = $success && set_field('question', 'qtype', 'numerical', 'qtype', 8);
        $success = $success && set_field('question', 'qtype', 'multianswer', 'qtype', 9);
        $success = $success && set_field('question', 'qtype', 'calculated', 'qtype', 10);
        $success = $success && set_field('question', 'qtype', 'rqp', 'qtype', 11);
        $success = $success && set_field('question', 'qtype', 'essay', 'qtype', 12);
    }
    if ($success && $oldversion < 2006032200) {
        // set version for all questiontypes that already have their tables installed
        $success = $success && set_config('qtype_calculated_version', 2006032100);
        $success = $success && set_config('qtype_essay_version', 2006032100);
        $success = $success && set_config('qtype_match_version', 2006032100);
        $success = $success && set_config('qtype_multianswer_version', 2006032100);
        $success = $success && set_config('qtype_multichoice_version', 2006032100);
        $success = $success && set_config('qtype_numerical_version', 2006032100);
        $success = $success && set_config('qtype_randomsamatch_version', 2006032100);
        $success = $success && set_config('qtype_rqp_version', 2006032100);
        $success = $success && set_config('qtype_shortanswer_version', 2006032100);
        $success = $success && set_config('qtype_truefalse_version', 2006032100);
    }
    if ($success && $oldversion < 2006040600) {
        $success = $success && table_column('question_sessions', '', 'comment', 'text', '', '', '', 'not null', 'sumpenalty');
    }
    if ($success && $oldversion < 2006040900) {
        $success = $success && modify_database('', "UPDATE prefix_question SET parent = id WHERE qtype ='random';");
    }
    if ($success && $oldversion < 2006041000) {
        $success = $success && modify_database('', " INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('quiz', 'continue attempt', 'quiz', 'name');");
    }
    if ($success && $oldversion < 2006041001) {
        $success = $success && table_column('question', 'version', 'version', 'varchar', 255);
    }
    if ($success && $oldversion < 2006042800) {
        // Check we have some un-renamed tables (verified in some servers)
        if ($tables = $db->MetaTables('TABLES')) {
            if (in_array($CFG->prefix . 'quiz_randommatch', $tables) && !in_array($CFG->prefix . 'question_randomsamatch', $tables)) {
                $success = $success && modify_database("", "ALTER TABLE prefix_quiz_randommatch RENAME prefix_question_randomsamatch ");
                $success = $success && modify_database("", "ALTER TABLE prefix_quiz_randommatch_id_seq RENAME prefix_question_randomsamatch_id_seq ");
                $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'question_randomsamatch ALTER COLUMN id SET DEFAULT nextval(\'' . $CFG->prefix . 'question_randomsamatch_id_seq\')');
            }
            // Check for one possible missing field in one table
            if ($columns = $db->MetaColumnNames($CFG->prefix . 'question_randomsamatch')) {
                if (!in_array('shuffleanswers', $columns)) {
                    $success = $success && table_column('question_randomsamatch', '', 'shuffleanswers', 'tinyint', '4', 'unsigned', '1', 'not null', 'choose');
                }
            }
        }
    }
    if ($success && $oldversion < 2006051300) {
        // this block also exec'ed by 2006042801 on MOODLE_16_STABLE
        // The newgraded field must always point to a valid state
        $success = $success && modify_database("", "UPDATE prefix_question_sessions SET newgraded = newest where newgraded = '0'");
        // Only perform this if hasn't been performed before (in MOODLE_16_STABLE branch - bug 5717)
        $tables = $db->MetaTables('TABLES');
        if (!in_array($CFG->prefix . 'question_attempts', $tables)) {
            // The following table is discussed in bug 5468
            $success = $success && modify_database("", "CREATE TABLE prefix_question_attempts (\n                                     id SERIAL PRIMARY KEY,\n                                     modulename varchar(20) NOT NULL default 'quiz'\n                                  );");
        }
    }
    if ($success && $oldversion < 2006051700) {
        // this block also exec'd by 2006042802 on MOODLE_16_STABLE
        notify("The next set of upgrade operations may report an \n                error if you are upgrading from v1.6. \n                This error mesage is normal, and can be ignored.");
        // this block is taken from mysql.php 2005070202
        // add new unique id to prepare the way for lesson module to have its own attempts table
        table_column('quiz_attempts', '', 'uniqueid', 'integer', '10', 'unsigned', '0', 'not null', 'id');
        // create one entry for all the existing quiz attempts
        // initially we can use the id as the unique id because no other modules use attempts yet.
        $success = $success && execute_sql("UPDATE {$CFG->prefix}quiz_attempts SET uniqueid = id");
        // we set $CFG->attemptuniqueid to the next available id
        $record = get_record_sql("SELECT nextval('{$CFG->prefix}quiz_attempts_id_seq')");
        $success = $success && set_config('attemptuniqueid', empty($record->nextid) ? 1 : $record->nextid);
        // the above will be a race condition, see bug 5468
        modify_database('', 'CREATE UNIQUE INDEX prefix_quiz_attempts_uniqueid_uk ON prefix_quiz_attempts (uniqueid);');
        // create one entry for all the existing quiz attempts
        $success = $success && modify_database("", "INSERT INTO prefix_question_attempts (id)\n                                   SELECT uniqueid\n                                   FROM prefix_quiz_attempts;");
    }
    if ($success && $oldversion < 2006042802) {
        // Copy the teacher comments from the question_essay_states table to the new
        // question_sessions table.
        // Get the attempt unique ID, teacher comment, graded flag, state ID, and question ID
        // based on the quesiont_essay_states
        if ($results = get_records_sql("SELECT a.uniqueid, es.response AS essaycomment, es.graded AS isgraded, \n                                               qs.id AS stateid, qs.question AS questionid \n                                        FROM {$CFG->prefix}question_states as qs,\n                                             {$CFG->prefix}question_essay_states es, \n                                             {$CFG->prefix}quiz_attempts a \n                                        WHERE es.stateid = qs.id AND a.uniqueid = qs.attempt")) {
            foreach ($results as $result) {
                // Create a state object to be used for updating
                $state = new stdClass();
                $state->id = $result->stateid;
                if ($result->isgraded) {
                    // Graded - save comment to the sessions and change state event to QUESTION_EVENTMANUALGRADE
                    if (!($success = $success && set_field('question_sessions', 'comment', $result->essaycomment, 'attemptid', $result->uniqueid, 'questionid', $result->questionid))) {
                        notify("Essay Table Migration: Cannot save comment");
                        break;
                    }
                    $state->event = 9;
                    //QUESTION_EVENTMANUALGRADE;
                } else {
                    // Not graded
                    $state->event = 7;
                    //QUESTION_EVENTSUBMIT;
                }
                // Save the event
                if (!($success = $success && update_record('question_states', $state))) {
                    notify("Essay Table Migration: Cannot update state");
                    break;
                }
            }
        }
        // dropping unused tables
        $success = $success && execute_sql('DROP TABLE ' . $CFG->prefix . 'question_essay_states');
        $success = $success && execute_sql('DROP TABLE ' . $CFG->prefix . 'question_essay');
        $success = $success && execute_sql('DROP TABLE ' . $CFG->prefix . 'quiz_attemptonlast_datasets');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question
            ALTER COLUMN qtype SET DEFAULT \'0\'');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question
            ALTER COLUMN version SET DEFAULT \'\'');
        // recreate the indexes that was not moved while quiz was transitioning to question lib
        $success && notify('Errors on indexes not being able to drop or already exists can be ignored as they may have been properly upgraded previously');
        $success && modify_database('', 'DROP INDEX prefix_quiz_numerical_answer_idx');
        $success && modify_database('', 'DROP INDEX prefix_quiz_numerical_question_idx');
        $success = $success && modify_database('', 'CREATE INDEX prefix_question_numerical_question_idx ON prefix_question_numerical (question)');
        $success = $success && modify_database('', 'CREATE INDEX prefix_question_numerical_answer_idx ON prefix_question_numerical (answer)');
        $success && modify_database('', 'DROP INDEX prefix_quiz_question_datasets_question_datasetdefinition_idx');
        $success = $success && modify_database('', 'CREATE INDEX prefix_question_datasets_question_datasetdefinition_idx ON prefix_question_datasets (question, datasetdefinition)');
        $success && modify_database('', 'DROP INDEX prefix_quiz_multichoice_question_idx');
        $success = $success && modify_database('', 'CREATE INDEX prefix_question_multichoice_question_idx ON prefix_question_multichoice (question)');
        $success && modify_database('', 'DROP INDEX prefix_quiz_categories_course_idx');
        $success = $success && modify_database('', 'CREATE INDEX prefix_question_categories_course_idx ON prefix_question_categories (course)');
        $success && modify_database('', 'DROP INDEX prefix_quiz_shortanswer_question_idx');
        $success = $success && modify_database('', 'CREATE INDEX prefix_question_shortanswer_question_idx ON prefix_question_shortanswer (question)');
        $success && modify_database('', 'DROP INDEX prefix_quiz_questions_category_idx');
        $success = $success && modify_database('', 'CREATE INDEX prefix_question_category_idx ON prefix_question (category)');
        $success && modify_database('', 'DROP INDEX prefix_quiz_calculated_answer_idx');
        $success && modify_database('', 'DROP INDEX prefix_quiz_calculated_question_idx');
        $success = $success && modify_database('', 'CREATE INDEX prefix_question_calculated_question_idx ON prefix_question_calculated (question)');
        $success = $success && modify_database('', 'CREATE INDEX prefix_question_calculated_answer_idx ON prefix_question_calculated (answer)');
        $success && modify_database('', 'DROP INDEX prefix_quiz_answers_question_idx');
        $success = $success && modify_database('', 'CREATE INDEX prefix_question_answers_question_idx ON prefix_question_answers (question)');
        $success && modify_database('', 'DROP INDEX prefix_quiz_dataset_items_definition_idx');
        $success = $success && modify_database('', 'CREATE INDEX prefix_question_dataset_items_definition_idx ON prefix_question_dataset_items (definition)');
        $success && modify_database('', 'DROP INDEX prefix_quiz_numerical_units_question_idx');
        $success = $success && modify_database('', 'CREATE INDEX prefix_question_numerical_units_question_idx ON prefix_question_numerical_units (question)');
        $success && modify_database('', 'DROP INDEX prefix_quiz_randomsamatch_question_idx');
        $success = $success && modify_database('', 'CREATE INDEX prefix_question_randomsamatch_question_idx ON prefix_question_randomsamatch (question)');
        $success && modify_database('', 'DROP INDEX prefix_quiz_states_question_idx');
        $success && modify_database('', 'DROP INDEX prefix_quiz_states_attempt_idx');
        $success = $success && modify_database('', 'CREATE INDEX prefix_question_states_question_idx ON prefix_question_states (question)');
        $success = $success && modify_database('', 'CREATE INDEX prefix_question_states_attempt_idx ON prefix_question_states (attempt)');
        $success && modify_database('', 'DROP INDEX prefix_quiz_match_question_idx');
        $success = $success && modify_database('', 'CREATE INDEX prefix_question_match_question_idx ON prefix_question_match (question)');
        $success && modify_database('', 'DROP INDEX prefix_quiz_match_sub_question_idx');
        $success = $success && modify_database('', 'CREATE INDEX prefix_question_match_sub_question_idx ON prefix_question_match_sub (question)');
        $success && modify_database('', 'DROP INDEX prefix_quiz_multianswers_question_idx');
        $success = $success && modify_database('', 'CREATE INDEX prefix_question_multianswer_question_idx ON prefix_question_multianswer (question)');
        $success && modify_database('', 'DROP INDEX prefix_quiz_dataset_definitions_category_idx');
        $success = $success && modify_database('', 'CREATE INDEX prefix_question_dataset_definitions_category_idx ON prefix_question_dataset_definitions (category)');
        $success = $success && modify_database('', 'CREATE INDEX prefix_log_timecoursemoduleaction_idx ON prefix_log ("time", course, module, "action")');
        $success = $success && modify_database('', 'CREATE INDEX prefix_log_coursemoduleaction_idx ON prefix_log (course, module, "action")');
        $success && modify_database('', 'DROP INDEX prefix_quiz_rqp_question_idx');
        $success = $success && modify_database('', 'CREATE INDEX prefix_question_rqp_question_idx ON prefix_question_rqp (question)');
        $success && modify_database('', 'DROP INDEX prefix_quiz_truefalse_question_idx');
        $success = $success && modify_database('', 'CREATE INDEX prefix_question_truefalse_question_idx ON prefix_question_truefalse (question)');
        $success && notify('End of upgrading of indexes');
        $success && notify('Renaming primary key names');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_numerical DROP CONSTRAINT prefix_quiz_numerical_pkey');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_numerical ADD CONSTRAINT prefix_question_numerical_pkey PRIMARY KEY (id)');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_datasets DROP CONSTRAINT prefix_quiz_question_datasets_pkey');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_datasets ADD CONSTRAINT prefix_question_datasets_pkey PRIMARY KEY (id)');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_multichoice DROP CONSTRAINT prefix_quiz_multichoice_pkey');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_multichoice ADD CONSTRAINT prefix_question_multichoice_pkey PRIMARY KEY (id)');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_rqp_states DROP CONSTRAINT prefix_quiz_rqp_states_pkey');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_rqp_states ADD CONSTRAINT prefix_question_rqp_states_pkey PRIMARY KEY (id)');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_categories DROP CONSTRAINT prefix_quiz_categories_pkey');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_categories ADD CONSTRAINT prefix_question_categories_pkey PRIMARY KEY (id)');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_shortanswer DROP CONSTRAINT prefix_quiz_shortanswer_pkey');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_shortanswer ADD CONSTRAINT prefix_question_shortanswer_pkey PRIMARY KEY (id)');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question DROP CONSTRAINT prefix_quiz_questions_pkey');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question ADD CONSTRAINT prefix_question_pkey PRIMARY KEY (id)');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_sessions DROP CONSTRAINT prefix_quiz_newest_states_pkey');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_sessions ADD CONSTRAINT prefix_question_sessions_pkey PRIMARY KEY (id)');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_calculated DROP CONSTRAINT prefix_quiz_calculated_pkey');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_calculated ADD CONSTRAINT prefix_question_calculated_pkey PRIMARY KEY (id)');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_answers DROP CONSTRAINT prefix_quiz_answers_pkey');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_answers ADD CONSTRAINT prefix_question_answers_pkey PRIMARY KEY (id)');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_dataset_items DROP CONSTRAINT prefix_quiz_dataset_items_pkey');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_dataset_items ADD CONSTRAINT prefix_question_dataset_items_pkey PRIMARY KEY (id)');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_numerical_units DROP CONSTRAINT prefix_quiz_numerical_units_pkey');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_numerical_units ADD CONSTRAINT prefix_question_numerical_units_pkey PRIMARY KEY (id)');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_randomsamatch DROP CONSTRAINT prefix_quiz_randomsamatch_pkey');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_randomsamatch ADD CONSTRAINT prefix_question_randomsamatch_pkey PRIMARY KEY (id)');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_rqp_types DROP CONSTRAINT prefix_quiz_rqp_types_pkey');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_rqp_types ADD CONSTRAINT prefix_question_rqp_types_pkey PRIMARY KEY (id)');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_states DROP CONSTRAINT prefix_quiz_states_pkey');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_states ADD CONSTRAINT prefix_question_states_pkey PRIMARY KEY (id)');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_match DROP CONSTRAINT prefix_quiz_match_pkey');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_match ADD CONSTRAINT prefix_question_match_pkey PRIMARY KEY (id)');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_match_sub DROP CONSTRAINT prefix_quiz_match_sub_pkey');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_match_sub ADD CONSTRAINT prefix_question_match_sub_pkey PRIMARY KEY (id)');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_multianswer DROP CONSTRAINT prefix_quiz_multianswers_pkey');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_multianswer ADD CONSTRAINT prefix_question_multianswer_pkey PRIMARY KEY (id)');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_dataset_definitions DROP CONSTRAINT prefix_quiz_dataset_definitions_pkey');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_dataset_definitions ADD CONSTRAINT prefix_question_dataset_definitions_pkey PRIMARY KEY (id)');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_rqp DROP CONSTRAINT prefix_quiz_rqp_pkey');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_rqp ADD CONSTRAINT prefix_question_rqp_pkey PRIMARY KEY (id)');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_truefalse DROP CONSTRAINT prefix_quiz_truefalse_pkey');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_truefalse ADD CONSTRAINT prefix_question_truefalse_pkey PRIMARY KEY (id)');
        $success && notify('End of renaming primary keys');
    }
    if ($oldversion < 2006081000) {
        // Add a column to the the question table to store the question general feedback.
        $success = $success && table_column('question', '', 'commentarytext', 'text', '', '', '', 'not null', 'image');
        // Adjust the quiz review options so that general feedback is displayed whenever feedback is.
        $success = $success && execute_sql('UPDATE ' . $CFG->prefix . 'quiz SET review = ' . '(review & ~' . QUIZ_REVIEW_GENERALFEEDBACK . ') | ' . '((review & ' . QUIZ_REVIEW_FEEDBACK . ') * 8)');
        // Set the general feedback bits to be the same as the feedback ones.
        // Same adjustment to the defaults for new quizzes.
        $success = $success && set_config('quiz_review', $CFG->quiz_review & ~QUIZ_REVIEW_GENERALFEEDBACK | ($CFG->quiz_review & QUIZ_REVIEW_FEEDBACK) << 3);
    }
    if ($success && $oldversion < 2006081400) {
        $success = $success && modify_database('', "\n            CREATE TABLE prefix_quiz_feedback (\n                id SERIAL PRIMARY KEY,\n                quizid integer NOT NULL default '0',\n                feedbacktext text NOT NULL default '',\n                maxgrade real NOT NULL default '0',\n                mingrade real NOT NULL default '0'\n            );\n        ");
        $success = $success && modify_database('', "CREATE INDEX prefix_quiz_feedback_quizid_idx ON prefix_quiz_feedback (quizid);");
        $success = $success && execute_sql("\n            INSERT INTO {$CFG->prefix}quiz_feedback (quizid, feedbacktext, maxgrade, mingrade)\n            SELECT id, '', grade + 1, 0 FROM {$CFG->prefix}quiz;\n        ");
    }
    if ($success && $oldversion < 2006082400) {
        $success = $success && table_column('question_sessions', 'comment', 'manualcomment', 'text', '', '', '');
    }
    if ($success && $oldversion < 2006091900) {
        $success = $success && table_column('question_dataset_items', 'number', 'itemnumber', 'integer');
    }
    if ($success && $oldversion < 2006091901) {
        $success = $success && table_column('question', 'commentarytext', 'generalfeedback', 'text', '', '', '');
    }
    //////  DO NOT ADD NEW THINGS HERE!!  USE upgrade.php and the lib/ddllib.php functions.
    return $success;
}
Ejemplo n.º 16
0
 /**
  * sync enrolments with database, create courses if required.
  *
  * @param object The role to sync for. If no role is specified, defaults are
  * used.
  */
 function sync_enrolments($role = null)
 {
     global $CFG;
     global $db;
     error_reporting(E_ALL);
     // Connect to the external database
     $enroldb = $this->enrol_connect();
     if (!$enroldb) {
         notify("enrol/database cannot connect to server");
         return false;
     }
     if (isset($role)) {
         echo '=== Syncing enrolments for role: ' . $role->shortname . " ===\n";
     } else {
         echo "=== Syncing enrolments for default role ===\n";
     }
     // first, pack the sortorder...
     fix_course_sortorder();
     list($have_role, $remote_role_name, $remote_role_value) = $this->role_fields($enroldb, $role);
     if (!$have_role) {
         if (!empty($CFG->enrol_db_defaultcourseroleid) and $role = get_record('role', 'id', $CFG->enrol_db_defaultcourseroleid)) {
             echo "=== Using enrol_db_defaultcourseroleid: {$role->id} ({$role->shortname}) ===\n";
         } elseif (isset($role)) {
             echo "!!! WARNING: Role specified by caller, but no (or invalid) role configuration !!!\n";
         }
     }
     // get enrolments per-course
     $sql = "SELECT DISTINCT {$CFG->enrol_remotecoursefield} " . " FROM {$CFG->enrol_dbtable} " . " WHERE {$CFG->enrol_remoteuserfield} IS NOT NULL" . (isset($remote_role_name, $remote_role_value) ? ' AND ' . $remote_role_name . ' = ' . $remote_role_value : '');
     $rs = $enroldb->Execute($sql);
     if (!$rs) {
         trigger_error($enroldb->ErrorMsg() . ' STATEMENT: ' . $sql);
         return false;
     }
     if ($rs->EOF) {
         // no courses! outta here...
         return true;
     }
     begin_sql();
     $extcourses = array();
     while ($extcourse_obj = rs_fetch_next_record($rs)) {
         // there are more course records
         $extcourse_obj = (object) array_change_key_case((array) $extcourse_obj, CASE_LOWER);
         $extcourse = $extcourse_obj->{strtolower($CFG->enrol_remotecoursefield)};
         array_push($extcourses, $extcourse);
         // does the course exist in moodle already?
         $course = false;
         $course = get_record('course', $CFG->enrol_localcoursefield, $extcourse);
         if (!is_object($course)) {
             if (empty($CFG->enrol_db_autocreate)) {
                 // autocreation not allowed
                 if (debugging('', DEBUG_ALL)) {
                     error_log("Course {$extcourse} does not exist, skipping");
                 }
                 continue;
                 // next foreach course
             }
             // ok, now then let's create it!
             // prepare any course properties we actually have
             $course = new StdClass();
             $course->{$CFG->enrol_localcoursefield} = $extcourse;
             $course->fullname = $extcourse;
             $course->shortname = $extcourse;
             if (!($newcourseid = $this->create_course($course, true) and $course = get_record('course', 'id', $newcourseid))) {
                 error_log("Creating course {$extcourse} failed");
                 continue;
                 // nothing left to do...
             }
         }
         $context = get_context_instance(CONTEXT_COURSE, $course->id);
         // If we don't have a proper role setup, then we default to the default
         // role for the current course.
         if (!$have_role) {
             $role = get_default_course_role($course);
         }
         // get a list of the student ids the are enrolled
         // in the external db -- hopefully it'll fit in memory...
         $extenrolments = array();
         $sql = "SELECT {$CFG->enrol_remoteuserfield} " . " FROM {$CFG->enrol_dbtable} " . " WHERE {$CFG->enrol_remotecoursefield} = " . $enroldb->quote($extcourse) . ($have_role ? ' AND ' . $remote_role_name . ' = ' . $remote_role_value : '');
         $crs = $enroldb->Execute($sql);
         if (!$crs) {
             trigger_error($enroldb->ErrorMsg() . ' STATEMENT: ' . $sql);
             return false;
         }
         if ($crs->EOF) {
             // shouldn't happen, but cover all bases
             continue;
         }
         // slurp results into an array
         while ($crs_obj = rs_fetch_next_record($crs)) {
             $crs_obj = (object) array_change_key_case((array) $crs_obj, CASE_LOWER);
             array_push($extenrolments, $crs_obj->{strtolower($CFG->enrol_remoteuserfield)});
         }
         rs_close($crs);
         // release the handle
         //
         // prune enrolments to users that are no longer in ext auth
         // hopefully they'll fit in the max buffer size for the RDBMS
         //
         // TODO: This doesn't work perfectly.  If we are operating without
         // roles in the external DB, then this doesn't handle changes of role
         // within a course (because the user is still enrolled in the course,
         // so NOT IN misses the course).
         //
         // When the user logs in though, their role list will be updated
         // correctly.
         //
         if (!$CFG->enrol_db_disableunenrol) {
             $to_prune = get_records_sql("\n             SELECT ra.*\n             FROM {$CFG->prefix}role_assignments ra\n              JOIN {$CFG->prefix}user u ON ra.userid = u.id\n             WHERE ra.enrol = 'database'\n              AND ra.contextid = {$context->id}\n              AND ra.roleid = " . $role->id . ($extenrolments ? " AND u.{$CFG->enrol_localuserfield} NOT IN (" . join(", ", array_map(array(&$db, 'quote'), $extenrolments)) . ")" : ''));
             if ($to_prune) {
                 foreach ($to_prune as $role_assignment) {
                     if (role_unassign($role->id, $role_assignment->userid, 0, $role_assignment->contextid)) {
                         error_log("Unassigned {$role->shortname} assignment #{$role_assignment->id} for course {$course->id} (" . format_string($course->shortname) . "); user {$role_assignment->userid}");
                     } else {
                         error_log("Failed to unassign {$role->shortname} assignment #{$role_assignment->id} for course {$course->id} (" . format_string($course->shortname) . "); user {$role_assignment->userid}");
                     }
                 }
             }
         }
         //
         // insert current enrolments
         // bad we can't do INSERT IGNORE with postgres...
         //
         foreach ($extenrolments as $member) {
             // Get the user id and whether is enrolled in one fell swoop
             $sql = "\n                SELECT u.id AS userid, ra.id AS enrolmentid\n                FROM {$CFG->prefix}user u\n                 LEFT OUTER JOIN {$CFG->prefix}role_assignments ra ON u.id = ra.userid\n                  AND ra.roleid = {$role->id}\n                  AND ra.contextid = {$context->id}\n                 WHERE u.{$CFG->enrol_localuserfield} = " . $db->quote($member) . " AND (u.deleted IS NULL OR u.deleted=0) ";
             $ers = $db->Execute($sql);
             if (!$ers) {
                 trigger_error($db->ErrorMsg() . ' STATEMENT: ' . $sql);
                 return false;
             }
             if ($ers->EOF) {
                 // if this returns empty, it means we don't have the student record.
                 // should not happen -- but skip it anyway
                 trigger_error('weird! no user record entry?');
                 continue;
             }
             $user_obj = rs_fetch_record($ers);
             $userid = $user_obj->userid;
             $enrolmentid = $user_obj->enrolmentid;
             rs_close($ers);
             // release the handle
             if ($enrolmentid) {
                 // already enrolled - skip
                 continue;
             }
             if (role_assign($role->id, $userid, 0, $context->id, 0, 0, 0, 'database')) {
                 error_log("Assigned role {$role->shortname} to user {$userid} in course {$course->id} (" . format_string($course->shortname) . ")");
             } else {
                 error_log("Failed to assign role {$role->shortname} to user {$userid} in course {$course->id} (" . format_string($course->shortname) . ")");
             }
         }
         // end foreach member
     }
     // end while course records
     rs_close($rs);
     //Close the main course recordset
     //
     // prune enrolments to courses that are no longer in ext auth
     //
     // TODO: This doesn't work perfectly.  If we are operating without
     // roles in the external DB, then this doesn't handle changes of role
     // within a course (because the user is still enrolled in the course,
     // so NOT IN misses the course).
     //
     // When the user logs in though, their role list will be updated
     // correctly.
     //
     if (!$CFG->enrol_db_disableunenrol) {
         $sql = "\n            SELECT ra.roleid, ra.userid, ra.contextid\n            FROM {$CFG->prefix}role_assignments ra\n                JOIN {$CFG->prefix}context cn ON cn.id = ra.contextid\n                JOIN {$CFG->prefix}course c ON c.id = cn.instanceid\n            WHERE ra.enrol = 'database'\n              AND cn.contextlevel = " . CONTEXT_COURSE . " " . ($have_role ? ' AND ra.roleid = ' . $role->id : '') . ($extcourses ? " AND c.{$CFG->enrol_localcoursefield} NOT IN (" . join(",", array_map(array(&$db, 'quote'), $extcourses)) . ")" : '');
         $ers = $db->Execute($sql);
         if (!$ers) {
             trigger_error($db->ErrorMsg() . ' STATEMENT: ' . $sql);
             return false;
         }
         if (!$ers->EOF) {
             while ($user_obj = rs_fetch_next_record($ers)) {
                 $user_obj = (object) array_change_key_case((array) $user_obj, CASE_LOWER);
                 $roleid = $user_obj->roleid;
                 $user = $user_obj->userid;
                 $contextid = $user_obj->contextid;
                 if (role_unassign($roleid, $user, 0, $contextid)) {
                     error_log("Unassigned role {$roleid} from user {$user} in context {$contextid}");
                 } else {
                     error_log("Failed unassign role {$roleid} from user {$user} in context {$contextid}");
                 }
             }
             rs_close($ers);
             // release the handle
         }
     }
     commit_sql();
     // we are done now, a bit of housekeeping
     fix_course_sortorder();
     $this->enrol_disconnect($enroldb);
     return true;
 }
Ejemplo n.º 17
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, 'mnethostid', (int) $logEntryObj->hostid);
             if ($logEntryObj->userid == false) {
                 $logEntryObj->userid = 0;
             }
             $useridarray[$logEntryObj->username] = $logEntryObj->userid;
         }
         unset($logEntryObj->username);
         $logEntryObj = $this->trim_logline($logEntryObj);
         $insertok = insert_record('mnet_log', addslashes_recursive($logEntryObj), false);
         if ($insertok) {
             $MNET_REMOTE_CLIENT->last_log_id = $logEntryObj->remoteid;
             $MNET_REMOTE_CLIENT->updateparams->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);
 }
Ejemplo n.º 18
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;
 }
Ejemplo n.º 19
0
/**
 * Marks user deleted in internal user database and notifies the auth plugin.
 * Also unenrols user from all roles and does other cleanup.
 * @param object $user       Userobject before delete    (without system magic quotes)
 * @return boolean success
 */
function delete_user($user)
{
    global $CFG;
    require_once $CFG->libdir . '/grouplib.php';
    require_once $CFG->libdir . '/gradelib.php';
    begin_sql();
    // delete all grades - backup is kept in grade_grades_history table
    if ($grades = grade_grade::fetch_all(array('userid' => $user->id))) {
        foreach ($grades as $grade) {
            $grade->delete('userdelete');
        }
    }
    // remove from all groups
    delete_records('groups_members', 'userid', $user->id);
    // unenrol from all roles in all contexts
    role_unassign(0, $user->id);
    // this might be slow but it is really needed - modules might do some extra cleanup!
    // now do a final accesslib cleanup - removes all role assingments in user context and context itself
    delete_context(CONTEXT_USER, $user->id);
    // mark internal user record as "deleted"
    $updateuser = new object();
    $updateuser->id = $user->id;
    $updateuser->deleted = 1;
    $updateuser->username = addslashes("{$user->email}." . time());
    // Remember it just in case
    $updateuser->email = '';
    // Clear this field to free it up
    $updateuser->idnumber = '';
    // Clear this field to free it up
    $updateuser->timemodified = time();
    if (update_record('user', $updateuser)) {
        commit_sql();
        // notify auth plugin - do not block the delete even when plugin fails
        $authplugin = get_auth_plugin($user->auth);
        $authplugin->user_delete($user);
        return true;
    } else {
        rollback_sql();
        return false;
    }
}
Ejemplo n.º 20
0
/**
 * The quiz grade is the score that student's results are marked out of. When it
 * changes, the corresponding data in quiz_grades and quiz_feedback needs to be
 * rescaled.
 *
 * @param float $newgrade the new maximum grade for the quiz.
 * @param object $quiz the quiz we are updating. Passed by reference so its grade field can be updated too.
 * @return boolean indicating success or failure.
 */
function quiz_set_grade($newgrade, &$quiz)
{
    // This is potentially expensive, so only do it if necessary.
    if (abs($quiz->grade - $newgrade) < 1.0E-7) {
        // Nothing to do.
        return true;
    }
    // Use a transaction, so that on those databases that support it, this is safer.
    begin_sql();
    // Update the quiz table.
    $success = set_field('quiz', 'grade', $newgrade, 'id', $quiz->instance);
    // Rescaling the other data is only possible if the old grade was non-zero.
    if ($quiz->grade > 1.0E-7) {
        global $CFG;
        $factor = $newgrade / $quiz->grade;
        $quiz->grade = $newgrade;
        // Update the quiz_grades table.
        $timemodified = time();
        $success = $success && execute_sql("\n                UPDATE {$CFG->prefix}quiz_grades\n                SET grade = {$factor} * grade, timemodified = {$timemodified}\n                WHERE quiz = {$quiz->id}\n        ", false);
        // Update the quiz_feedback table.
        $success = $success && execute_sql("\n                UPDATE {$CFG->prefix}quiz_feedback\n                SET mingrade = {$factor} * mingrade, maxgrade = {$factor} * maxgrade\n                WHERE quizid = {$quiz->id}\n        ", false);
    }
    // update grade item and send all grades to gradebook
    quiz_grade_item_update($quiz);
    quiz_update_grades($quiz);
    if ($success) {
        return commit_sql();
    } else {
        rollback_sql();
        return false;
    }
}
Ejemplo n.º 21
0
/**
 * Fetch a record from the rollover queue and process it.
 *
 * @param int $id The ID of the request to process.
 * @return bool True on success, False otherwise.
 */
function process_queue($id = FALSE)
{
    global $CFG, $USER;
    require_once $CFG->dirroot . '/message/lib.php';
    begin_sql();
    if ($id) {
        $task = get_record('block_admin_rollover_queue', 'id', $id);
        if (!$task) {
            commit_sql();
            notify(get_string('queue_notfound', 'rollover'), 'notifyproblem errorbox');
            return FALSE;
        }
    } else {
        $task = get_record('block_admin_rollover_queue', '', '');
        if (!$task) {
            commit_sql();
            return FALSE;
        }
    }
    print_heading(get_string('run_queue_record', 'rollover', $task));
    flush();
    // make sure we don't have multiple entries for the course
    $status = delete_records('block_admin_course_template', 'courseid', $task->courseid);
    $status = $status && delete_records('block_admin_rollover_queue', 'id', $task->id);
    $status = $status && content_rollover($task->templateid, $task->courseid);
    $trec = new stdClass();
    $trec->courseid = $task->courseid;
    $trec->templateid = $task->templateid;
    $trec->timemodified = time();
    $status = $status && ($trec->id = insert_record('block_admin_course_template', $trec));
    if ($status) {
        commit_sql();
        $touser = get_record('user', 'id', $task->userid);
        $coursename = get_field('course', 'fullname', 'id', $task->courseid);
        $a = new stdClass();
        $a->coursename = get_field('course', 'fullname', 'id', $task->courseid);
        $a->link = '<a href="' . $CFG->wwwroot . '/course/view.php?id=' . $task->courseid . '">' . $coursename . '</a>';
        print_heading(get_string('rollover_message', 'rollover', $a));
        message_post_message($USER, $touser, get_string('rollover_message', 'rollover', $a), FORMAT_HTML, 'direct');
        notify(get_string('success'), 'notifysuccess');
        return TRUE;
    } else {
        rollback_sql();
        notify(get_string('rollover_failure', 'rollover'), 'notifyproblem errorbox');
        return FALSE;
    }
}