Exemplo n.º 1
0
function xmldb_assignment_upgrade($oldversion) {
    global $CFG, $DB, $OUTPUT;

    $dbman = $DB->get_manager();


    // Moodle v2.2.0 release upgrade line
    // Put any upgrade step following this

    // Moodle v2.3.0 release upgrade line
    // Put any upgrade step following this


    if ($oldversion < 2012061701) {
        // Fixed/updated numfiles field in assignment_submissions table to count the actual
        // number of files has been uploaded when sendformarking is disabled
        upgrade_set_timeout(600);  // increase excution time for in large sites
        $fs = get_file_storage();

        // Fetch the moduleid for use in the course_modules table
        $moduleid = $DB->get_field('modules', 'id', array('name' => 'assignment'), MUST_EXIST);

        $selectcount = 'SELECT COUNT(s.id) ';
        $select      = 'SELECT s.id, cm.id AS cmid ';
        $query       = 'FROM {assignment_submissions} s
                        JOIN {assignment} a ON a.id = s.assignment
                        JOIN {course_modules} cm ON a.id = cm.instance AND cm.module = :moduleid
                        WHERE assignmenttype = :assignmenttype';

        $params = array('moduleid' => $moduleid, 'assignmenttype' => 'upload');

        $countsubmissions = $DB->count_records_sql($selectcount.$query, $params);
        $submissions = $DB->get_recordset_sql($select.$query, $params);

        $pbar = new progress_bar('assignmentupgradenumfiles', 500, true);
        $i = 0;
        foreach ($submissions as $sub) {
            $i++;
            if ($context = context_module::instance($sub->cmid)) {
                $sub->numfiles = count($fs->get_area_files($context->id, 'mod_assignment', 'submission', $sub->id, 'sortorder', false));
                $DB->update_record('assignment_submissions', $sub);
            }
            $pbar->update($i, $countsubmissions, "Counting files of submissions ($i/$countsubmissions)");
        }
        $submissions->close();

        // assignment savepoint reached
        upgrade_mod_savepoint(true, 2012061701, 'assignment');
    }

    // Moodle v2.4.0 release upgrade line
    // Put any upgrade step following this


    // Moodle v2.5.0 release upgrade line.
    // Put any upgrade step following this.


    return true;
}
Exemplo n.º 2
0
/**
 * Installation code for the ddmarker question type. It converts all existing imagetarget questions to ddmarker
 */
function xmldb_qtype_ddmarker_install()
{
    global $DB, $OUTPUT;
    $from = 'FROM {question_categories} cat, {question} q';
    $where = ' WHERE q.qtype = \'imagetarget\' AND q.category =  cat.id ';
    $sql = 'SELECT q.*, cat.contextid ' . $from . $where . 'ORDER BY cat.id, q.name';
    $questions = $DB->get_records_sql($sql);
    if (!empty($questions)) {
        require_once dirname(__FILE__) . '/../lib.php';
        $dragssql = 'SELECT drag.* ' . $from . ', {qtype_ddmarker_drags} drag' . $where . ' AND drag.questionid = q.id';
        $drags = xmldb_qtype_ddmarker_index_array_of_records_by_key('questionid', $DB->get_records_sql($dragssql));
        $dropssql = 'SELECT drp.* ' . $from . ', {qtype_ddmarker_drops} drp' . $where . ' AND drp.questionid = q.id';
        $drops = xmldb_qtype_ddmarker_index_array_of_records_by_key('questionid', $DB->get_records_sql($dropssql));
        $answerssql = 'SELECT answer.* ' . $from . ', {question_answers} answer' . $where . ' AND answer.question = q.id';
        $answers = xmldb_qtype_ddmarker_index_array_of_records_by_key('question', $DB->get_records_sql($answerssql));
        $imgfiles = $DB->get_records_sql_menu('SELECT question, qimage FROM {question_imagetarget}');
        $progressbar = new progress_bar('qtype_ddmarker_convert_from_imagetarget');
        $progressbar->create();
        $done = 0;
        foreach ($questions as $question) {
            qtype_ddmarker_convert_image_target_question($question, $imgfiles[$question->id], $answers[$question->id]);
            $done++;
            $progressbar->update($done, count($questions), get_string('convertingimagetargetquestion', 'qtype_ddmarker', $question));
        }
        list($qsql, $qparams) = $DB->get_in_or_equal(array_keys($questions));
        $DB->delete_records_select('question_answers', 'question ' . $qsql, $qparams);
        $dbman = $DB->get_manager();
        $dbman->drop_table(new xmldb_table('question_imagetarget'));
    }
}
Exemplo n.º 3
0
    /**
     * Called before starting to upgrade all the attempts at a particular quiz.
     * @param int $done the number of quizzes processed so far.
     * @param int $outof the total number of quizzes to process.
     * @param int $quizid the id of the quiz that is about to be processed.
     */
    protected function print_progress($done, $outof, $quizid) {
        if (is_null($this->progressbar)) {
            $this->progressbar = new progress_bar('qe2upgrade');
            $this->progressbar->create();
        }

        gc_collect_cycles(); // This was really helpful in PHP 5.2. Perhaps remove.
        $a = new stdClass();
        $a->done = $done;
        $a->outof = $outof;
        $a->info = $quizid;
        $this->progressbar->update($done, $outof, get_string('upgradingquizattempts', 'quiz', $a));
    }
Exemplo n.º 4
0
/**
 * Upgrade code for the essay question type.
 * @param int $oldversion the version we are upgrading from.
 */
function xmldb_qtype_essay_upgrade($oldversion)
{
    global $CFG, $DB;
    $dbman = $DB->get_manager();
    // Moodle v2.2.0 release upgrade line
    // Put any upgrade step following this
    if ($oldversion < 2011102701) {
        $sql = "\n                  FROM {question} q\n                  JOIN {question_answers} qa ON qa.question = q.id\n\n                 WHERE q.qtype = 'essay'\n                   AND " . $DB->sql_isnotempty('question_answers', 'feedback', false, true);
        // In Moodle <= 2.0 essay had both question.generalfeedback and question_answers.feedback.
        // This was silly, and in Moodel >= 2.1 only question.generalfeedback. To avoid
        // dataloss, we concatenate question_answers.feedback onto the end of question.generalfeedback.
        $count = $DB->count_records_sql("\n                SELECT COUNT(1) {$sql}");
        if ($count) {
            $progressbar = new progress_bar('essay23', 500, true);
            $done = 0;
            $toupdate = $DB->get_recordset_sql("\n                    SELECT q.id,\n                           q.generalfeedback,\n                           q.generalfeedbackformat,\n                           qa.feedback,\n                           qa.feedbackformat\n                    {$sql}");
            foreach ($toupdate as $data) {
                $progressbar->update($done, $count, "Updating essay feedback ({$done}/{$count}).");
                upgrade_set_timeout(60);
                if ($data->generalfeedbackformat == $data->feedbackformat) {
                    $DB->set_field('question', 'generalfeedback', $data->generalfeedback . $data->feedback, array('id' => $data->id));
                } else {
                    $newdata = new stdClass();
                    $newdata->id = $data->id;
                    $newdata->generalfeedback = qtype_essay_convert_to_html($data->generalfeedback, $data->generalfeedbackformat) . qtype_essay_convert_to_html($data->feedback, $data->feedbackformat);
                    $newdata->generalfeedbackformat = FORMAT_HTML;
                    $DB->update_record('question', $newdata);
                }
            }
            $progressbar->update($count, $count, "Updating essay feedback complete!");
            $toupdate->close();
        }
        // Essay savepoint reached.
        upgrade_plugin_savepoint(true, 2011102701, 'qtype', 'essay');
    }
    if ($oldversion < 2011102702) {
        // Then we delete the old question_answers rows for essay questions.
        $DB->delete_records_select('question_answers', "question IN (SELECT id FROM {question} WHERE qtype = 'essay')");
        // Essay savepoint reached.
        upgrade_plugin_savepoint(true, 2011102702, 'qtype', 'essay');
    }
    // Moodle v2.3.0 release upgrade line
    // Put any upgrade step following this
    // Moodle v2.4.0 release upgrade line
    // Put any upgrade step following this
    return true;
}
Exemplo n.º 5
0
 /**
  * Segmente le document numérique et stocke le résultat en base de données
  */
 public function diarize()
 {
     // On commence par supprimer
     $query = "delete from explnum_segments where explnum_segment_explnum_num = " . $this->explnum->explnum_id;
     mysql_query($query);
     $query = "delete from explnum_speakers where explnum_speaker_explnum_num = " . $this->explnum->explnum_id;
     mysql_query($query);
     // Gestion de la progress_bar
     $progress_bar = new progress_bar("upload to server");
     $progress_bar->set_percent(0);
     $this->speechFile = $this->diarization->sendFile($this->getFile());
     // 		$this->speechFile = $this->diarization->getFile(67);
     $status = $this->speechFile->getStatus();
     while ($status != "diarization_phase7") {
         if ($status == "uploaded") {
             $progress_bar->set_percent(round(1 / 8 * 100));
         } else {
             $nb = str_replace("diarization_phase", "", $status);
             $progress_bar->set_percent(round(($nb + 1) / 8 * 100));
         }
         $progress_bar->set_text($status);
         $status = $this->speechFile->getStatus();
         sleep(0.5);
     }
     sleep(10);
     $progress_bar->hide();
     $speakers = $this->speechFile->getSpeakers();
     $speakers_ids = array();
     // Tableau associant l'identifiant du speaker avec son identifiant dans la table
     foreach ($speakers as $speaker) {
         $query = "insert into explnum_speakers (explnum_speaker_explnum_num, explnum_speaker_speaker_num, explnum_speaker_gender) values (" . $this->explnum->explnum_id . ", '" . $speaker->getID() . "', '" . $speaker->getGender() . "')";
         mysql_query($query);
         $speakers_ids[$speaker->getID()] = mysql_insert_id();
     }
     $segments = $this->speechFile->getSegments();
     foreach ($segments as $segment) {
         $query = "insert into explnum_segments (explnum_segment_explnum_num, explnum_segment_speaker_num, explnum_segment_start, explnum_segment_duration, explnum_segment_end) values (" . $this->explnum->explnum_id . ", '" . $speakers_ids[$segment->getSpeaker()->getID()] . "', " . $segment->getStart() . ", " . $segment->getDuration() . ", " . $segment->getEnd() . ")";
         mysql_query($query);
     }
 }
/**
 * Migrate geogebra package to new area if found
 *
 * @return
 */
function geogebra_migrate_files()
{
    global $CFG, $DB;
    $fs = get_file_storage();
    $sqlfrom = "FROM {geogebra} j\n                JOIN {modules} m ON m.name = 'geogebra'\n                JOIN {course_modules} cm ON (cm.module = m.id AND cm.instance = j.id)";
    $count = $DB->count_records_sql("SELECT COUNT('x') {$sqlfrom}");
    $rs = $DB->get_recordset_sql("SELECT j.id, j.url, j.course, cm.id AS cmid {$sqlfrom} ORDER BY j.course, j.id");
    if ($rs->valid()) {
        $pbar = new progress_bar('migrategeogebrafiles', 500, true);
        $i = 0;
        foreach ($rs as $geogebra) {
            $i++;
            upgrade_set_timeout(180);
            // set up timeout, may also abort execution
            $pbar->update($i, $count, "Migrating geogebra files - {$i}/{$count}.");
            $context = context_module::instance($geogebra->cmid);
            $coursecontext = context_course::instance($geogebra->course);
            if (!geogebra_is_valid_external_url($geogebra->url)) {
                // first copy local files if found - do not delete in case they are shared ;-)
                $geogebrafile = clean_param($geogebra->url, PARAM_PATH);
                $pathnamehash = sha1("/{$coursecontext->id}/course/legacy/0/{$geogebrafile}");
                if ($file = $fs->get_file_by_hash($pathnamehash)) {
                    $file_record = array('contextid' => $context->id, 'component' => 'mod_geogebra', 'filearea' => 'content', 'itemid' => 0, 'filepath' => '/');
                    try {
                        $fs->create_file_from_storedfile($file_record, $file);
                    } catch (Exception $x) {
                        // ignore any errors, we can not do much anyway
                    }
                    $geogebra->url = $pathnamehash;
                } else {
                    $geogebra->url = '';
                }
                $DB->update_record('geogebra', $geogebra);
            }
        }
    }
    $rs->close();
}
Exemplo n.º 7
0
/**
 * Migrate all text and binary columns to big size - mysql only.
 */
function upgrade_mysql_fix_lob_columns()
{
    // we are not using standard API for changes of column intentionally
    global $DB;
    if ($DB->get_dbfamily() !== 'mysql') {
        return;
    }
    $pbar = new progress_bar('mysqlconvertlobs', 500, true);
    $prefix = $DB->get_prefix();
    $tables = $DB->get_tables();
    asort($tables);
    $tablecount = count($tables);
    $i = 0;
    foreach ($tables as $table) {
        $i++;
        // set appropriate timeout - 1 minute per thousand of records should be enough, min 60 minutes just in case
        $count = $DB->count_records($table, array());
        $timeout = $count / 1000 * 60;
        $timeout = $timeout < 60 * 60 ? 60 * 60 : (int) $timeout;
        $sql = "SHOW COLUMNS FROM `{{$table}}`";
        $rs = $DB->get_recordset_sql($sql);
        foreach ($rs as $column) {
            upgrade_set_timeout($timeout);
            $column = (object) array_change_key_case((array) $column, CASE_LOWER);
            if ($column->type === 'tinytext' or $column->type === 'mediumtext' or $column->type === 'text') {
                $notnull = $column->null === 'NO' ? 'NOT NULL' : 'NULL';
                $default = (!is_null($column->default) and $column->default !== '') ? "DEFAULT '{$column->default}'" : '';
                // primary, unique and inc are not supported for texts
                $sql = "ALTER TABLE `{$prefix}{$table}` MODIFY COLUMN `{$column->field}` LONGTEXT {$notnull} {$default}";
                $DB->change_database_structure($sql);
            }
            if ($column->type === 'tinyblob' or $column->type === 'mediumblob' or $column->type === 'blob') {
                $notnull = $column->null === 'NO' ? 'NOT NULL' : 'NULL';
                $default = (!is_null($column->default) and $column->default !== '') ? "DEFAULT '{$column->default}'" : '';
                // primary, unique and inc are not supported for blobs
                $sql = "ALTER TABLE `{$prefix}{$table}` MODIFY COLUMN `{$column->field}` LONGBLOB {$notnull} {$default}";
                $DB->change_database_structure($sql);
            }
        }
        $rs->close();
        $pbar->update($i, $tablecount, "Converted LOB columns in MySQL database - {$i}/{$tablecount}.");
    }
}
Exemplo n.º 8
0
/**
 * Main upgrade tasks to be executed on Moodle version bump
 *
 * This function is automatically executed after one bump in the Moodle core
 * version is detected. It's in charge of performing the required tasks
 * to raise core from the previous version to the next one.
 *
 * It's a collection of ordered blocks of code, named "upgrade steps",
 * each one performing one isolated (from the rest of steps) task. Usually
 * tasks involve creating new DB objects or performing manipulation of the
 * information for cleanup/fixup purposes.
 *
 * Each upgrade step has a fixed structure, that can be summarised as follows:
 *
 * if ($oldversion < XXXXXXXXXX.XX) {
 *     // Explanation of the update step, linking to issue in the Tracker if necessary
 *     upgrade_set_timeout(XX); // Optional for big tasks
 *     // Code to execute goes here, usually the XMLDB Editor will
 *     // help you here. See {@link http://docs.moodle.org/dev/XMLDB_editor}.
 *     upgrade_main_savepoint(true, XXXXXXXXXX.XX);
 * }
 *
 * All plugins within Moodle (modules, blocks, reports...) support the existence of
 * their own upgrade.php file, using the "Frankenstyle" component name as
 * defined at {@link http://docs.moodle.org/dev/Frankenstyle}, for example:
 *     - {@link xmldb_page_upgrade($oldversion)}. (modules don't require the plugintype ("mod_") to be used.
 *     - {@link xmldb_auth_manual_upgrade($oldversion)}.
 *     - {@link xmldb_workshopform_accumulative_upgrade($oldversion)}.
 *     - ....
 *
 * In order to keep the contents of this file reduced, it's allowed to create some helper
 * functions to be used here in the {@link upgradelib.php} file at the same directory. Note
 * that such a file must be manually included from upgrade.php, and there are some restrictions
 * about what can be used within it.
 *
 * For more information, take a look to the documentation available:
 *     - Data definition API: {@link http://docs.moodle.org/dev/Data_definition_API}
 *     - Upgrade API: {@link http://docs.moodle.org/dev/Upgrade_API}
 *
 * @param int $oldversion
 * @return bool always true
 */
function xmldb_main_upgrade($oldversion)
{
    global $CFG, $DB;
    require_once $CFG->libdir . '/db/upgradelib.php';
    // Core Upgrade-related functions.
    $dbman = $DB->get_manager();
    // Loads ddl manager and xmldb classes.
    // Always keep this upgrade step with version being the minimum
    // allowed version to upgrade from (v2.7.0 right now).
    if ($oldversion < 2014051200) {
        // Just in case somebody hacks upgrade scripts or env, we really can not continue.
        echo "You need to upgrade to 2.7.x or higher first!\n";
        exit(1);
        // Note this savepoint is 100% unreachable, but needed to pass the upgrade checks.
        upgrade_main_savepoint(true, 2014051200);
    }
    // MDL-32543 Make sure that the log table has correct length for action and url fields.
    if ($oldversion < 2014051200.02) {
        $table = new xmldb_table('log');
        $columns = $DB->get_columns('log');
        if ($columns['action']->max_length < 40) {
            $index1 = new xmldb_index('course-module-action', XMLDB_INDEX_NOTUNIQUE, array('course', 'module', 'action'));
            if ($dbman->index_exists($table, $index1)) {
                $dbman->drop_index($table, $index1);
            }
            $index2 = new xmldb_index('action', XMLDB_INDEX_NOTUNIQUE, array('action'));
            if ($dbman->index_exists($table, $index2)) {
                $dbman->drop_index($table, $index2);
            }
            $field = new xmldb_field('action', XMLDB_TYPE_CHAR, '40', null, XMLDB_NOTNULL, null, null, 'cmid');
            $dbman->change_field_precision($table, $field);
            $dbman->add_index($table, $index1);
            $dbman->add_index($table, $index2);
        }
        if ($columns['url']->max_length < 100) {
            $field = new xmldb_field('url', XMLDB_TYPE_CHAR, '100', null, XMLDB_NOTNULL, null, null, 'action');
            $dbman->change_field_precision($table, $field);
        }
        upgrade_main_savepoint(true, 2014051200.02);
    }
    if ($oldversion < 2014060300.0) {
        $gspath = get_config('assignfeedback_editpdf', 'gspath');
        if ($gspath !== false) {
            set_config('pathtogs', $gspath);
            unset_config('gspath', 'assignfeedback_editpdf');
        }
        upgrade_main_savepoint(true, 2014060300.0);
    }
    if ($oldversion < 2014061000.0) {
        // Fixing possible wrong MIME type for Publisher files.
        $filetypes = array('%.pub' => 'application/x-mspublisher');
        upgrade_mimetypes($filetypes);
        upgrade_main_savepoint(true, 2014061000.0);
    }
    if ($oldversion < 2014062600.01) {
        // We only want to delete DragMath if the directory no longer exists. If the directory
        // is present then it means it has been restored, so do not perform the uninstall.
        if (!check_dir_exists($CFG->libdir . '/editor/tinymce/plugins/dragmath', false)) {
            // Purge DragMath plugin which is incompatible with GNU GPL license.
            unset_all_config_for_plugin('tinymce_dragmath');
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2014062600.01);
    }
    // Switch the order of the fields in the files_reference index, to improve the performance of search_references.
    if ($oldversion < 2014070100.0) {
        $table = new xmldb_table('files_reference');
        $index = new xmldb_index('uq_external_file', XMLDB_INDEX_UNIQUE, array('repositoryid', 'referencehash'));
        if ($dbman->index_exists($table, $index)) {
            $dbman->drop_index($table, $index);
        }
        upgrade_main_savepoint(true, 2014070100.0);
    }
    if ($oldversion < 2014070101.0) {
        $table = new xmldb_table('files_reference');
        $index = new xmldb_index('uq_external_file', XMLDB_INDEX_UNIQUE, array('referencehash', 'repositoryid'));
        if (!$dbman->index_exists($table, $index)) {
            $dbman->add_index($table, $index);
        }
        upgrade_main_savepoint(true, 2014070101.0);
    }
    if ($oldversion < 2014072400.01) {
        $table = new xmldb_table('user_devices');
        $oldindex = new xmldb_index('pushid-platform', XMLDB_KEY_UNIQUE, array('pushid', 'platform'));
        if ($dbman->index_exists($table, $oldindex)) {
            $key = new xmldb_key('pushid-platform', XMLDB_KEY_UNIQUE, array('pushid', 'platform'));
            $dbman->drop_key($table, $key);
        }
        upgrade_main_savepoint(true, 2014072400.01);
    }
    if ($oldversion < 2014080801.0) {
        // Define index behaviour (not unique) to be added to question_attempts.
        $table = new xmldb_table('question_attempts');
        $index = new xmldb_index('behaviour', XMLDB_INDEX_NOTUNIQUE, array('behaviour'));
        // Conditionally launch add index behaviour.
        if (!$dbman->index_exists($table, $index)) {
            $dbman->add_index($table, $index);
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2014080801.0);
    }
    if ($oldversion < 2014082900.01) {
        // Fixing possible wrong MIME type for 7-zip and Rar files.
        $filetypes = array('%.7z' => 'application/x-7z-compressed', '%.rar' => 'application/x-rar-compressed');
        upgrade_mimetypes($filetypes);
        upgrade_main_savepoint(true, 2014082900.01);
    }
    if ($oldversion < 2014082900.02) {
        // Replace groupmembersonly usage with new availability system.
        $transaction = $DB->start_delegated_transaction();
        if ($CFG->enablegroupmembersonly) {
            // If it isn't already enabled, we need to enable availability.
            if (!$CFG->enableavailability) {
                set_config('enableavailability', 1);
            }
            // Count all course-modules with groupmembersonly set (for progress
            // bar).
            $total = $DB->count_records('course_modules', array('groupmembersonly' => 1));
            $pbar = new progress_bar('upgradegroupmembersonly', 500, true);
            // Get all these course-modules, one at a time.
            $rs = $DB->get_recordset('course_modules', array('groupmembersonly' => 1), 'course, id');
            $i = 0;
            foreach ($rs as $cm) {
                // Calculate and set new availability value.
                $availability = upgrade_group_members_only($cm->groupingid, $cm->availability);
                $DB->set_field('course_modules', 'availability', $availability, array('id' => $cm->id));
                // Update progress.
                $i++;
                $pbar->update($i, $total, "Upgrading groupmembersonly settings - {$i}/{$total}.");
            }
            $rs->close();
        }
        // Define field groupmembersonly to be dropped from course_modules.
        $table = new xmldb_table('course_modules');
        $field = new xmldb_field('groupmembersonly');
        // Conditionally launch drop field groupmembersonly.
        if ($dbman->field_exists($table, $field)) {
            $dbman->drop_field($table, $field);
        }
        // Unset old config variable.
        unset_config('enablegroupmembersonly');
        $transaction->allow_commit();
        upgrade_main_savepoint(true, 2014082900.02);
    }
    if ($oldversion < 2014100100.0) {
        // Define table messageinbound_handlers to be created.
        $table = new xmldb_table('messageinbound_handlers');
        // Adding fields to table messageinbound_handlers.
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
        $table->add_field('component', XMLDB_TYPE_CHAR, '100', null, XMLDB_NOTNULL, null, null);
        $table->add_field('classname', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null);
        $table->add_field('defaultexpiration', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '86400');
        $table->add_field('validateaddress', XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, '1');
        $table->add_field('enabled', XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, '0');
        // Adding keys to table messageinbound_handlers.
        $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->add_key('classname', XMLDB_KEY_UNIQUE, array('classname'));
        // Conditionally launch create table for messageinbound_handlers.
        if (!$dbman->table_exists($table)) {
            $dbman->create_table($table);
        }
        // Define table messageinbound_datakeys to be created.
        $table = new xmldb_table('messageinbound_datakeys');
        // Adding fields to table messageinbound_datakeys.
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
        $table->add_field('handler', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null);
        $table->add_field('datavalue', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null);
        $table->add_field('datakey', XMLDB_TYPE_CHAR, '64', null, null, null, null);
        $table->add_field('timecreated', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null);
        $table->add_field('expires', XMLDB_TYPE_INTEGER, '10', null, null, null, null);
        // Adding keys to table messageinbound_datakeys.
        $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->add_key('handler_datavalue', XMLDB_KEY_UNIQUE, array('handler', 'datavalue'));
        $table->add_key('handler', XMLDB_KEY_FOREIGN, array('handler'), 'messageinbound_handlers', array('id'));
        // Conditionally launch create table for messageinbound_datakeys.
        if (!$dbman->table_exists($table)) {
            $dbman->create_table($table);
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2014100100.0);
    }
    if ($oldversion < 2014100600.01) {
        // Define field aggregationstatus to be added to grade_grades.
        $table = new xmldb_table('grade_grades');
        $field = new xmldb_field('aggregationstatus', XMLDB_TYPE_CHAR, '10', null, XMLDB_NOTNULL, null, 'unknown', 'timemodified');
        // Conditionally launch add field aggregationstatus.
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        $field = new xmldb_field('aggregationweight', XMLDB_TYPE_NUMBER, '10, 5', null, null, null, null, 'aggregationstatus');
        // Conditionally launch add field aggregationweight.
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        // Define field aggregationcoef2 to be added to grade_items.
        $table = new xmldb_table('grade_items');
        $field = new xmldb_field('aggregationcoef2', XMLDB_TYPE_NUMBER, '10, 5', null, XMLDB_NOTNULL, null, '0', 'aggregationcoef');
        // Conditionally launch add field aggregationcoef2.
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        $field = new xmldb_field('weightoverride', XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, '0', 'needsupdate');
        // Conditionally launch add field weightoverride.
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2014100600.01);
    }
    if ($oldversion < 2014100600.02) {
        // Define field aggregationcoef2 to be added to grade_items_history.
        $table = new xmldb_table('grade_items_history');
        $field = new xmldb_field('aggregationcoef2', XMLDB_TYPE_NUMBER, '10, 5', null, XMLDB_NOTNULL, null, '0', 'aggregationcoef');
        // Conditionally launch add field aggregationcoef2.
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2014100600.02);
    }
    if ($oldversion < 2014100600.03) {
        // Define field weightoverride to be added to grade_items_history.
        $table = new xmldb_table('grade_items_history');
        $field = new xmldb_field('weightoverride', XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, '0', 'decimals');
        // Conditionally launch add field weightoverride.
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2014100600.03);
    }
    if ($oldversion < 2014100600.04) {
        // Set flags so we can display a notice on all courses that might
        // be affected by the uprade to natural aggregation.
        if (!get_config('grades_sumofgrades_upgrade_flagged', 'core')) {
            // 13 == SUM_OF_GRADES.
            $sql = 'SELECT DISTINCT courseid
                      FROM {grade_categories}
                     WHERE aggregation = ?';
            $courses = $DB->get_records_sql($sql, array(13));
            foreach ($courses as $course) {
                set_config('show_sumofgrades_upgrade_' . $course->courseid, 1);
                // Set each of the grade items to needing an update so that when the user visits the grade reports the
                // figures will be updated.
                $DB->set_field('grade_items', 'needsupdate', 1, array('courseid' => $course->courseid));
            }
            set_config('grades_sumofgrades_upgrade_flagged', 1);
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2014100600.04);
    }
    if ($oldversion < 2014100700.0) {
        // Define table messageinbound_messagelist to be created.
        $table = new xmldb_table('messageinbound_messagelist');
        // Adding fields to table messageinbound_messagelist.
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
        $table->add_field('messageid', XMLDB_TYPE_TEXT, null, null, XMLDB_NOTNULL, null, null);
        $table->add_field('userid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null);
        $table->add_field('address', XMLDB_TYPE_TEXT, null, null, XMLDB_NOTNULL, null, null);
        $table->add_field('timecreated', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null);
        // Adding keys to table messageinbound_messagelist.
        $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->add_key('userid', XMLDB_KEY_FOREIGN, array('userid'), 'user', array('id'));
        // Conditionally launch create table for messageinbound_messagelist.
        if (!$dbman->table_exists($table)) {
            $dbman->create_table($table);
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2014100700.0);
    }
    if ($oldversion < 2014100700.01) {
        // Define field visible to be added to cohort.
        $table = new xmldb_table('cohort');
        $field = new xmldb_field('visible', XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, '1', 'descriptionformat');
        // Conditionally launch add field visible.
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2014100700.01);
    }
    if ($oldversion < 2014100800.0) {
        // Remove qformat_learnwise (unless it has manually been added back).
        if (!file_exists($CFG->dirroot . '/question/format/learnwise/format.php')) {
            unset_all_config_for_plugin('qformat_learnwise');
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2014100800.0);
    }
    if ($oldversion < 2014101001.0) {
        // Some blocks added themselves to the my/ home page, but they did not declare the
        // subpage of the default my home page. While the upgrade script has been fixed, this
        // upgrade script will fix the data that was wrongly added.
        // We only proceed if we can find the right entry from my_pages. Private => 1 refers to
        // the constant value MY_PAGE_PRIVATE.
        if ($systempage = $DB->get_record('my_pages', array('userid' => null, 'private' => 1))) {
            // Select the blocks there could have been automatically added. showinsubcontexts is hardcoded to 0
            // because it is possible for administrators to have forced it on the my/ page by adding it to the
            // system directly rather than updating the default my/ page.
            $blocks = array('course_overview', 'private_files', 'online_users', 'badges', 'calendar_month', 'calendar_upcoming');
            list($blocksql, $blockparams) = $DB->get_in_or_equal($blocks, SQL_PARAMS_NAMED);
            $select = "parentcontextid = :contextid\n                    AND pagetypepattern = :page\n                    AND showinsubcontexts = 0\n                    AND subpagepattern IS NULL\n                    AND blockname {$blocksql}";
            $params = array('contextid' => context_system::instance()->id, 'page' => 'my-index');
            $params = array_merge($params, $blockparams);
            $DB->set_field_select('block_instances', 'subpagepattern', $systempage->id, $select, $params);
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2014101001.0);
    }
    if ($oldversion < 2014102000.0) {
        // Define field aggregatesubcats to be dropped from grade_categories.
        $table = new xmldb_table('grade_categories');
        $field = new xmldb_field('aggregatesubcats');
        // Conditionally launch drop field aggregatesubcats.
        if ($dbman->field_exists($table, $field)) {
            $sql = 'SELECT DISTINCT courseid
                      FROM {grade_categories}
                     WHERE aggregatesubcats = ?';
            $courses = $DB->get_records_sql($sql, array(1));
            foreach ($courses as $course) {
                set_config('show_aggregatesubcats_upgrade_' . $course->courseid, 1);
                // Set each of the grade items to needing an update so that when the user visits the grade reports the
                // figures will be updated.
                $DB->set_field('grade_items', 'needsupdate', 1, array('courseid' => $course->courseid));
            }
            $dbman->drop_field($table, $field);
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2014102000.0);
    }
    if ($oldversion < 2014110300.0) {
        // Run script restoring missing folder records for draft file areas.
        upgrade_fix_missing_root_folders_draft();
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2014110300.0);
    }
    // Moodle v2.8.0 release upgrade line.
    // Put any upgrade step following this.
    if ($oldversion < 2014111000.0) {
        // Coming from 2.7 or older, we need to flag the step minmaxgrade to be ignored.
        set_config('upgrade_minmaxgradestepignored', 1);
        // Coming from 2.7 or older, we need to flag the step for changing calculated grades to be regraded.
        set_config('upgrade_calculatedgradeitemsonlyregrade', 1);
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2014111000.0);
    }
    if ($oldversion < 2014120100.0) {
        // Define field sslverification to be added to mnet_host.
        $table = new xmldb_table('mnet_host');
        $field = new xmldb_field('sslverification', XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, '0', 'applicationid');
        // Conditionally launch add field sslverification.
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2014120100.0);
    }
    if ($oldversion < 2014120101.0) {
        // Define field component to be added to comments.
        $table = new xmldb_table('comments');
        $field = new xmldb_field('component', XMLDB_TYPE_CHAR, '255', null, null, null, null, 'contextid');
        // Conditionally launch add field component.
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2014120101.0);
    }
    if ($oldversion < 2014120102.0) {
        // Define table user_password_history to be created.
        $table = new xmldb_table('user_password_history');
        // Adding fields to table user_password_history.
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
        $table->add_field('userid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null);
        $table->add_field('hash', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null);
        $table->add_field('timecreated', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null);
        // Adding keys to table user_password_history.
        $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->add_key('userid', XMLDB_KEY_FOREIGN, array('userid'), 'user', array('id'));
        // Conditionally launch create table for user_password_history.
        if (!$dbman->table_exists($table)) {
            $dbman->create_table($table);
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2014120102.0);
    }
    if ($oldversion < 2015010800.01) {
        // Make sure the private files handler is not set to expire.
        $DB->set_field('messageinbound_handlers', 'defaultexpiration', 0, array('classname' => '\\core\\message\\inbound\\private_files_handler'));
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2015010800.01);
    }
    if ($oldversion < 2015012600.0) {
        // If the site is using internal and external storage, or just external
        // storage, and the external path specified is empty we change the setting
        // to internal only. That is how the backup code is handling this
        // misconfiguration.
        $storage = (int) get_config('backup', 'backup_auto_storage');
        $folder = get_config('backup', 'backup_auto_destination');
        if ($storage !== 0 && empty($folder)) {
            set_config('backup_auto_storage', 0, 'backup');
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2015012600.0);
    }
    if ($oldversion < 2015012600.01) {
        // Convert calendar_lookahead to nearest new value.
        $value = $DB->get_field('config', 'value', array('name' => 'calendar_lookahead'));
        if ($value > 90) {
            set_config('calendar_lookahead', '120');
        } else {
            if ($value > 60 and $value < 90) {
                set_config('calendar_lookahead', '90');
            } else {
                if ($value > 30 and $value < 60) {
                    set_config('calendar_lookahead', '60');
                } else {
                    if ($value > 21 and $value < 30) {
                        set_config('calendar_lookahead', '30');
                    } else {
                        if ($value > 14 and $value < 21) {
                            set_config('calendar_lookahead', '21');
                        } else {
                            if ($value > 7 and $value < 14) {
                                set_config('calendar_lookahead', '14');
                            }
                        }
                    }
                }
            }
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2015012600.01);
    }
    if ($oldversion < 2015021100.0) {
        // Define field timemodified to be added to registration_hubs.
        $table = new xmldb_table('registration_hubs');
        $field = new xmldb_field('timemodified', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0', 'secret');
        // Conditionally launch add field timemodified.
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2015021100.0);
    }
    if ($oldversion < 2015022401.0) {
        // Define index useridfromto (not unique) to be added to message.
        $table = new xmldb_table('message');
        $index = new xmldb_index('useridfromto', XMLDB_INDEX_NOTUNIQUE, array('useridfrom', 'useridto'));
        // Conditionally launch add index useridfromto.
        if (!$dbman->index_exists($table, $index)) {
            $dbman->add_index($table, $index);
        }
        // Define index useridfromto (not unique) to be added to message_read.
        $table = new xmldb_table('message_read');
        $index = new xmldb_index('useridfromto', XMLDB_INDEX_NOTUNIQUE, array('useridfrom', 'useridto'));
        // Conditionally launch add index useridfromto.
        if (!$dbman->index_exists($table, $index)) {
            $dbman->add_index($table, $index);
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2015022401.0);
    }
    if ($oldversion < 2015022500.0) {
        $table = new xmldb_table('user_devices');
        $index = new xmldb_index('uuid-userid', XMLDB_INDEX_NOTUNIQUE, array('uuid', 'userid'));
        if (!$dbman->index_exists($table, $index)) {
            $dbman->add_index($table, $index);
        }
        upgrade_main_savepoint(true, 2015022500.0);
    }
    if ($oldversion < 2015030400.0) {
        // We have long since switched to storing timemodified per hub rather than a single 'registered' timestamp.
        unset_config('registered');
        upgrade_main_savepoint(true, 2015030400.0);
    }
    if ($oldversion < 2015031100.0) {
        // Unset old config variable.
        unset_config('enabletgzbackups');
        upgrade_main_savepoint(true, 2015031100.0);
    }
    if ($oldversion < 2015031400.0) {
        // Define index useridfrom (not unique) to be dropped form message.
        $table = new xmldb_table('message');
        $index = new xmldb_index('useridfrom', XMLDB_INDEX_NOTUNIQUE, array('useridfrom'));
        // Conditionally launch drop index useridfrom.
        if ($dbman->index_exists($table, $index)) {
            $dbman->drop_index($table, $index);
        }
        // Define index useridfrom (not unique) to be dropped form message_read.
        $table = new xmldb_table('message_read');
        $index = new xmldb_index('useridfrom', XMLDB_INDEX_NOTUNIQUE, array('useridfrom'));
        // Conditionally launch drop index useridfrom.
        if ($dbman->index_exists($table, $index)) {
            $dbman->drop_index($table, $index);
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2015031400.0);
    }
    if ($oldversion < 2015031900.01) {
        unset_config('crontime', 'registration');
        upgrade_main_savepoint(true, 2015031900.01);
    }
    if ($oldversion < 2015032000.0) {
        $table = new xmldb_table('badge_criteria');
        $field = new xmldb_field('description', XMLDB_TYPE_TEXT, null, null, null, null, null);
        // Conditionally add description field to the badge_criteria table.
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        $field = new xmldb_field('descriptionformat', XMLDB_TYPE_INTEGER, 2, null, XMLDB_NOTNULL, null, 0);
        // Conditionally add description format field to the badge_criteria table.
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        upgrade_main_savepoint(true, 2015032000.0);
    }
    if ($oldversion < 2015040200.01) {
        // Force uninstall of deleted tool.
        if (!file_exists("{$CFG->dirroot}/{$CFG->admin}/tool/timezoneimport")) {
            // Remove capabilities.
            capabilities_cleanup('tool_timezoneimport');
            // Remove all other associated config.
            unset_all_config_for_plugin('tool_timezoneimport');
        }
        upgrade_main_savepoint(true, 2015040200.01);
    }
    if ($oldversion < 2015040200.02) {
        // Define table timezone to be dropped.
        $table = new xmldb_table('timezone');
        // Conditionally launch drop table for timezone.
        if ($dbman->table_exists($table)) {
            $dbman->drop_table($table);
        }
        upgrade_main_savepoint(true, 2015040200.02);
    }
    if ($oldversion < 2015040200.03) {
        if (isset($CFG->timezone) and $CFG->timezone == 99) {
            // Migrate to real server timezone.
            unset_config('timezone');
        }
        upgrade_main_savepoint(true, 2015040200.03);
    }
    if ($oldversion < 2015040700.01) {
        $DB->delete_records('config_plugins', array('name' => 'requiremodintro'));
        upgrade_main_savepoint(true, 2015040700.01);
    }
    if ($oldversion < 2015040900.01) {
        // Add "My grades" to the user menu.
        $oldconfig = get_config('core', 'customusermenuitems');
        if (strpos("mygrades,grades|/grade/report/mygrades.php|grades", $oldconfig) === false) {
            $newconfig = "mygrades,grades|/grade/report/mygrades.php|grades\n" . $oldconfig;
            set_config('customusermenuitems', $newconfig);
        }
        upgrade_main_savepoint(true, 2015040900.01);
    }
    if ($oldversion < 2015040900.02) {
        // Update the default user menu (add preferences, remove my files and my badges).
        $oldconfig = get_config('core', 'customusermenuitems');
        // Add "My preferences" at the end.
        if (strpos($oldconfig, "mypreferences,moodle|/user/preference.php|preferences") === false) {
            $newconfig = $oldconfig . "\nmypreferences,moodle|/user/preferences.php|preferences";
        } else {
            $newconfig = $oldconfig;
        }
        // Remove my files.
        $newconfig = str_replace("myfiles,moodle|/user/files.php|download", "", $newconfig);
        // Remove my badges.
        $newconfig = str_replace("mybadges,badges|/badges/mybadges.php|award", "", $newconfig);
        // Remove holes.
        $newconfig = preg_replace('/\\n+/', "\n", $newconfig);
        $newconfig = preg_replace('/(\\r\\n)+/', "\n", $newconfig);
        set_config('customusermenuitems', $newconfig);
        upgrade_main_savepoint(true, 2015040900.02);
    }
    if ($oldversion < 2015050400.0) {
        $config = get_config('core', 'customusermenuitems');
        // Change "My preferences" in the user menu to "Preferences".
        $config = str_replace("mypreferences,moodle|/user/preferences.php|preferences", "preferences,moodle|/user/preferences.php|preferences", $config);
        // Change "My grades" in the user menu to "Grades".
        $config = str_replace("mygrades,grades|/grade/report/mygrades.php|grades", "grades,grades|/grade/report/mygrades.php|grades", $config);
        set_config('customusermenuitems', $config);
        upgrade_main_savepoint(true, 2015050400.0);
    }
    if ($oldversion < 2015050401.0) {
        // Make sure we have messages in the user menu because it's no longer in the nav tree.
        $oldconfig = get_config('core', 'customusermenuitems');
        $messagesconfig = "messages,message|/message/index.php|message";
        $preferencesconfig = "preferences,moodle|/user/preferences.php|preferences";
        // See if it exists.
        if (strpos($oldconfig, $messagesconfig) === false) {
            // See if preferences exists.
            if (strpos($oldconfig, "preferences,moodle|/user/preferences.php|preferences") !== false) {
                // Insert it before preferences.
                $newconfig = str_replace($preferencesconfig, $messagesconfig . "\n" . $preferencesconfig, $oldconfig);
            } else {
                // Custom config - we can only insert it at the end.
                $newconfig = $oldconfig . "\n" . $messagesconfig;
            }
            set_config('customusermenuitems', $newconfig);
        }
        upgrade_main_savepoint(true, 2015050401.0);
    }
    // Moodle v2.9.0 release upgrade line.
    // Put any upgrade step following this.
    if ($oldversion < 2015060400.02) {
        // Sites that were upgrading from 2.7 and older will ignore this step.
        if (empty($CFG->upgrade_minmaxgradestepignored)) {
            upgrade_minmaxgrade();
            // Flags this upgrade step as already run to prevent it from running multiple times.
            set_config('upgrade_minmaxgradestepignored', 1);
        }
        upgrade_main_savepoint(true, 2015060400.02);
    }
    if ($oldversion < 2015061900.0) {
        // MDL-49257. Changed the algorithm of calculating automatic weights of extra credit items.
        // Before the change, in case when grade category (in "Natural" agg. method) had items with
        // overridden weights, the automatic weight of extra credit items was illogical.
        // In order to prevent grades changes after the upgrade we need to freeze gradebook calculation
        // for the affected courses.
        // This script in included in each major version upgrade process so make sure we don't run it twice.
        if (empty($CFG->upgrade_extracreditweightsstepignored)) {
            upgrade_extra_credit_weightoverride();
            // To skip running the same script on the upgrade to the next major release.
            set_config('upgrade_extracreditweightsstepignored', 1);
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2015061900.0);
    }
    if ($oldversion < 2015062500.01) {
        // MDL-48239. Changed calculated grade items so that the maximum and minimum grade can be set.
        // If the changes are accepted and a regrade is done on the gradebook then some grades may change significantly.
        // This is here to freeze the gradebook in affected courses.
        // This script is included in each major version upgrade process so make sure we don't run it twice.
        if (empty($CFG->upgrade_calculatedgradeitemsignored)) {
            upgrade_calculated_grade_items();
            // To skip running the same script on the upgrade to the next major release.
            set_config('upgrade_calculatedgradeitemsignored', 1);
            // This config value is never used again.
            unset_config('upgrade_calculatedgradeitemsonlyregrade');
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2015062500.01);
    }
    if ($oldversion < 2015081300.01) {
        // Define field importtype to be added to grade_import_values.
        $table = new xmldb_table('grade_import_values');
        $field = new xmldb_field('importonlyfeedback', XMLDB_TYPE_INTEGER, '1', null, null, null, '0', 'importer');
        // Conditionally launch add field importtype.
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2015081300.01);
    }
    if ($oldversion < 2015082400.0) {
        // Define table webdav_locks to be dropped.
        $table = new xmldb_table('webdav_locks');
        // Conditionally launch drop table for webdav_locks.
        if ($dbman->table_exists($table)) {
            $dbman->drop_table($table);
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2015082400.0);
    }
    if ($oldversion < 2015090200.0) {
        $table = new xmldb_table('message');
        // Define the deleted fields to be added to the message tables.
        $field1 = new xmldb_field('timeuserfromdeleted', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0', 'timecreated');
        $field2 = new xmldb_field('timeusertodeleted', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0', 'timecreated');
        $oldindex = new xmldb_index('useridfromto', XMLDB_INDEX_NOTUNIQUE, array('useridfrom', 'useridto'));
        $newindex = new xmldb_index('useridfromtodeleted', XMLDB_INDEX_NOTUNIQUE, array('useridfrom', 'useridto', 'timeuserfromdeleted', 'timeusertodeleted'));
        // Conditionally launch add field timeuserfromdeleted.
        if (!$dbman->field_exists($table, $field1)) {
            $dbman->add_field($table, $field1);
        }
        // Conditionally launch add field timeusertodeleted.
        if (!$dbman->field_exists($table, $field2)) {
            $dbman->add_field($table, $field2);
        }
        // Conditionally launch drop index useridfromto.
        if ($dbman->index_exists($table, $oldindex)) {
            $dbman->drop_index($table, $oldindex);
        }
        // Conditionally launch add index useridfromtodeleted.
        if (!$dbman->index_exists($table, $newindex)) {
            $dbman->add_index($table, $newindex);
        }
        // Now add them to the message_read table.
        $table = new xmldb_table('message_read');
        // Conditionally launch add field timeuserfromdeleted.
        if (!$dbman->field_exists($table, $field1)) {
            $dbman->add_field($table, $field1);
        }
        // Conditionally launch add field timeusertodeleted.
        if (!$dbman->field_exists($table, $field2)) {
            $dbman->add_field($table, $field2);
        }
        // Conditionally launch drop index useridfromto.
        if ($dbman->index_exists($table, $oldindex)) {
            $dbman->drop_index($table, $oldindex);
        }
        // Conditionally launch add index useridfromtodeleted.
        if (!$dbman->index_exists($table, $newindex)) {
            $dbman->add_index($table, $newindex);
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2015090200.0);
    }
    if ($oldversion < 2015090801.0) {
        // This upgrade script merges all tag instances pointing to the same course tag.
        // User id is no longer used for those tag instances.
        upgrade_course_tags();
        // If configuration variable "Show course tags" is set, disable the block
        // 'tags' because it can not be used for tagging courses any more.
        if (!empty($CFG->block_tags_showcoursetags)) {
            if ($record = $DB->get_record('block', array('name' => 'tags'), 'id, visible')) {
                if ($record->visible) {
                    $DB->update_record('block', array('id' => $record->id, 'visible' => 0));
                }
            }
        }
        // Define index idname (unique) to be dropped form tag (it's really weird).
        $table = new xmldb_table('tag');
        $index = new xmldb_index('idname', XMLDB_INDEX_UNIQUE, array('id', 'name'));
        // Conditionally launch drop index idname.
        if ($dbman->index_exists($table, $index)) {
            $dbman->drop_index($table, $index);
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2015090801.0);
    }
    if ($oldversion < 2015092200.0) {
        // Define index qtype (not unique) to be added to question.
        $table = new xmldb_table('question');
        $index = new xmldb_index('qtype', XMLDB_INDEX_NOTUNIQUE, array('qtype'));
        // Conditionally launch add index qtype.
        if (!$dbman->index_exists($table, $index)) {
            $dbman->add_index($table, $index);
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2015092200.0);
    }
    if ($oldversion < 2015092900.0) {
        // Rename backup_auto_keep setting to backup_auto_max_kept.
        $keep = get_config('backup', 'backup_auto_keep');
        if ($keep !== false) {
            set_config('backup_auto_max_kept', $keep, 'backup');
            unset_config('backup_auto_keep', 'backup');
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2015092900.0);
    }
    if ($oldversion < 2015100600.0) {
        // Define index notification (not unique) to be added to message_read.
        $table = new xmldb_table('message_read');
        $index = new xmldb_index('notificationtimeread', XMLDB_INDEX_NOTUNIQUE, array('notification', 'timeread'));
        // Conditionally launch add index notification.
        if (!$dbman->index_exists($table, $index)) {
            $dbman->add_index($table, $index);
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2015100600.0);
    }
    if ($oldversion < 2015100800.01) {
        // The only flag for preventing all plugins installation features is
        // now $CFG->disableupdateautodeploy in config.php.
        unset_config('updateautodeploy');
        upgrade_main_savepoint(true, 2015100800.01);
    }
    // Moodle v3.0.0 release upgrade line.
    // Put any upgrade step following this.
    if ($oldversion < 2016011300.01) {
        // This is a big upgrade script. We create new table tag_coll and the field
        // tag.tagcollid pointing to it.
        // Define table tag_coll to be created.
        $table = new xmldb_table('tag_coll');
        // Adding fields to table tagcloud.
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
        $table->add_field('name', XMLDB_TYPE_CHAR, '255', null, null, null, null);
        $table->add_field('isdefault', XMLDB_TYPE_INTEGER, '2', null, XMLDB_NOTNULL, null, '0');
        $table->add_field('component', XMLDB_TYPE_CHAR, '100', null, null, null, null);
        $table->add_field('sortorder', XMLDB_TYPE_INTEGER, '5', null, XMLDB_NOTNULL, null, '0');
        $table->add_field('searchable', XMLDB_TYPE_INTEGER, '2', null, XMLDB_NOTNULL, null, '1');
        $table->add_field('customurl', XMLDB_TYPE_CHAR, '255', null, null, null, null);
        // Adding keys to table tagcloud.
        $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
        // Conditionally launch create table for tagcloud.
        if (!$dbman->table_exists($table)) {
            $dbman->create_table($table);
        }
        // Table {tag}.
        // Define index name (unique) to be dropped form tag - we will replace it with index on (tagcollid,name) later.
        $table = new xmldb_table('tag');
        $index = new xmldb_index('name', XMLDB_INDEX_UNIQUE, array('name'));
        // Conditionally launch drop index name.
        if ($dbman->index_exists($table, $index)) {
            $dbman->drop_index($table, $index);
        }
        // Define field tagcollid to be added to tag, we create it as null first and will change to notnull later.
        $table = new xmldb_table('tag');
        $field = new xmldb_field('tagcollid', XMLDB_TYPE_INTEGER, '10', null, null, null, null, 'userid');
        // Conditionally launch add field tagcloudid.
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2016011300.01);
    }
    if ($oldversion < 2016011300.02) {
        // Create a default tag collection if not exists and update the field tag.tagcollid to point to it.
        if (!($tcid = $DB->get_field_sql('SELECT id FROM {tag_coll} ORDER BY isdefault DESC, sortorder, id', null, IGNORE_MULTIPLE))) {
            $tcid = $DB->insert_record('tag_coll', array('isdefault' => 1, 'sortorder' => 0));
        }
        $DB->execute('UPDATE {tag} SET tagcollid = ? WHERE tagcollid IS NULL', array($tcid));
        // Define index tagcollname (unique) to be added to tag.
        $table = new xmldb_table('tag');
        $index = new xmldb_index('tagcollname', XMLDB_INDEX_UNIQUE, array('tagcollid', 'name'));
        $field = new xmldb_field('tagcollid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, 'userid');
        // Conditionally launch add index tagcollname.
        if (!$dbman->index_exists($table, $index)) {
            // Launch change of nullability for field tagcollid.
            $dbman->change_field_notnull($table, $field);
            $dbman->add_index($table, $index);
        }
        // Define key tagcollid (foreign) to be added to tag.
        $table = new xmldb_table('tag');
        $key = new xmldb_key('tagcollid', XMLDB_KEY_FOREIGN, array('tagcollid'), 'tag_coll', array('id'));
        // Launch add key tagcloudid.
        $dbman->add_key($table, $key);
        // Define index tagcolltype (not unique) to be added to tag.
        $table = new xmldb_table('tag');
        $index = new xmldb_index('tagcolltype', XMLDB_INDEX_NOTUNIQUE, array('tagcollid', 'tagtype'));
        // Conditionally launch add index tagcolltype.
        if (!$dbman->index_exists($table, $index)) {
            $dbman->add_index($table, $index);
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2016011300.02);
    }
    if ($oldversion < 2016011300.03) {
        // Define table tag_area to be created.
        $table = new xmldb_table('tag_area');
        // Adding fields to table tag_area.
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
        $table->add_field('component', XMLDB_TYPE_CHAR, '100', null, XMLDB_NOTNULL, null, null);
        $table->add_field('itemtype', XMLDB_TYPE_CHAR, '100', null, XMLDB_NOTNULL, null, null);
        $table->add_field('enabled', XMLDB_TYPE_INTEGER, '2', null, XMLDB_NOTNULL, null, '1');
        $table->add_field('tagcollid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null);
        $table->add_field('callback', XMLDB_TYPE_CHAR, '100', null, null, null, null);
        $table->add_field('callbackfile', XMLDB_TYPE_CHAR, '100', null, null, null, null);
        // Adding keys to table tag_area.
        $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->add_key('tagcollid', XMLDB_KEY_FOREIGN, array('tagcollid'), 'tag_coll', array('id'));
        // Adding indexes to table tag_area.
        $table->add_index('compitemtype', XMLDB_INDEX_UNIQUE, array('component', 'itemtype'));
        // Conditionally launch create table for tag_area.
        if (!$dbman->table_exists($table)) {
            $dbman->create_table($table);
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2016011300.03);
    }
    if ($oldversion < 2016011300.04) {
        // Define index itemtype-itemid-tagid-tiuserid (unique) to be dropped form tag_instance.
        $table = new xmldb_table('tag_instance');
        $index = new xmldb_index('itemtype-itemid-tagid-tiuserid', XMLDB_INDEX_UNIQUE, array('itemtype', 'itemid', 'tagid', 'tiuserid'));
        // Conditionally launch drop index itemtype-itemid-tagid-tiuserid.
        if ($dbman->index_exists($table, $index)) {
            $dbman->drop_index($table, $index);
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2016011300.04);
    }
    if ($oldversion < 2016011300.05) {
        $DB->execute("UPDATE {tag_instance} SET component = ? WHERE component IS NULL", array(''));
        // Changing nullability of field component on table tag_instance to not null.
        $table = new xmldb_table('tag_instance');
        $field = new xmldb_field('component', XMLDB_TYPE_CHAR, '100', null, XMLDB_NOTNULL, null, null, 'tagid');
        // Launch change of nullability for field component.
        $dbman->change_field_notnull($table, $field);
        // Changing type of field itemtype on table tag_instance to char.
        $table = new xmldb_table('tag_instance');
        $field = new xmldb_field('itemtype', XMLDB_TYPE_CHAR, '100', null, XMLDB_NOTNULL, null, null, 'component');
        // Launch change of type for field itemtype.
        $dbman->change_field_type($table, $field);
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2016011300.05);
    }
    if ($oldversion < 2016011300.06) {
        // Define index taggeditem (unique) to be added to tag_instance.
        $table = new xmldb_table('tag_instance');
        $index = new xmldb_index('taggeditem', XMLDB_INDEX_UNIQUE, array('component', 'itemtype', 'itemid', 'tiuserid', 'tagid'));
        // Conditionally launch add index taggeditem.
        if (!$dbman->index_exists($table, $index)) {
            $dbman->add_index($table, $index);
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2016011300.06);
    }
    if ($oldversion < 2016011300.07) {
        // Define index taglookup (not unique) to be added to tag_instance.
        $table = new xmldb_table('tag_instance');
        $index = new xmldb_index('taglookup', XMLDB_INDEX_NOTUNIQUE, array('itemtype', 'component', 'tagid', 'contextid'));
        // Conditionally launch add index taglookup.
        if (!$dbman->index_exists($table, $index)) {
            $dbman->add_index($table, $index);
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2016011300.07);
    }
    if ($oldversion < 2016011301.0) {
        // Force uninstall of deleted tool.
        if (!file_exists("{$CFG->dirroot}/webservice/amf")) {
            // Remove capabilities.
            capabilities_cleanup('webservice_amf');
            // Remove all other associated config.
            unset_all_config_for_plugin('webservice_amf');
        }
        upgrade_main_savepoint(true, 2016011301.0);
    }
    if ($oldversion < 2016011901.0) {
        // Convert calendar_lookahead to nearest new value.
        $transaction = $DB->start_delegated_transaction();
        // Count all users who curretly have that preference set (for progress bar).
        $total = $DB->count_records_select('user_preferences', "name = 'calendar_lookahead' AND value != '0'");
        $pbar = new progress_bar('upgradecalendarlookahead', 500, true);
        // Get all these users, one at a time.
        $rs = $DB->get_recordset_select('user_preferences', "name = 'calendar_lookahead' AND value != '0'");
        $i = 0;
        foreach ($rs as $userpref) {
            // Calculate and set new lookahead value.
            if ($userpref->value > 90) {
                $newvalue = 120;
            } else {
                if ($userpref->value > 60 and $userpref->value < 90) {
                    $newvalue = 90;
                } else {
                    if ($userpref->value > 30 and $userpref->value < 60) {
                        $newvalue = 60;
                    } else {
                        if ($userpref->value > 21 and $userpref->value < 30) {
                            $newvalue = 30;
                        } else {
                            if ($userpref->value > 14 and $userpref->value < 21) {
                                $newvalue = 21;
                            } else {
                                if ($userpref->value > 7 and $userpref->value < 14) {
                                    $newvalue = 14;
                                } else {
                                    $newvalue = $userpref->value;
                                }
                            }
                        }
                    }
                }
            }
            $DB->set_field('user_preferences', 'value', $newvalue, array('id' => $userpref->id));
            // Update progress.
            $i++;
            $pbar->update($i, $total, "Upgrading user preference settings - {$i}/{$total}.");
        }
        $rs->close();
        $transaction->allow_commit();
        upgrade_main_savepoint(true, 2016011901.0);
    }
    if ($oldversion < 2016020200.0) {
        // Define field isstandard to be added to tag.
        $table = new xmldb_table('tag');
        $field = new xmldb_field('isstandard', XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, '0', 'rawname');
        // Conditionally launch add field isstandard.
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        // Define index tagcolltype (not unique) to be dropped form tag.
        $index = new xmldb_index('tagcolltype', XMLDB_INDEX_NOTUNIQUE, array('tagcollid', 'tagtype'));
        // Conditionally launch drop index tagcolltype.
        if ($dbman->index_exists($table, $index)) {
            $dbman->drop_index($table, $index);
        }
        // Define index tagcolltype (not unique) to be added to tag.
        $index = new xmldb_index('tagcolltype', XMLDB_INDEX_NOTUNIQUE, array('tagcollid', 'isstandard'));
        // Conditionally launch add index tagcolltype.
        if (!$dbman->index_exists($table, $index)) {
            $dbman->add_index($table, $index);
        }
        // Define field tagtype to be dropped from tag.
        $field = new xmldb_field('tagtype');
        // Conditionally launch drop field tagtype and update isstandard.
        if ($dbman->field_exists($table, $field)) {
            $DB->execute("UPDATE {tag} SET isstandard=(CASE WHEN (tagtype = ?) THEN 1 ELSE 0 END)", array('official'));
            $dbman->drop_field($table, $field);
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2016020200.0);
    }
    if ($oldversion < 2016020201.0) {
        // Define field showstandard to be added to tag_area.
        $table = new xmldb_table('tag_area');
        $field = new xmldb_field('showstandard', XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, '0', 'callbackfile');
        // Conditionally launch add field showstandard.
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        // By default set user area to hide standard tags. 2 = core_tag_tag::HIDE_STANDARD (can not use constant here).
        $DB->execute("UPDATE {tag_area} SET showstandard = ? WHERE itemtype = ? AND component = ?", array(2, 'user', 'core'));
        // Changing precision of field enabled on table tag_area to (1).
        $table = new xmldb_table('tag_area');
        $field = new xmldb_field('enabled', XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, '1', 'itemtype');
        // Launch change of precision for field enabled.
        $dbman->change_field_precision($table, $field);
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2016020201.0);
    }
    if ($oldversion < 2016021500.0) {
        $root = $CFG->tempdir . '/download';
        if (is_dir($root)) {
            // Fetch each repository type - include all repos, not just enabled.
            $repositories = $DB->get_records('repository', array(), '', 'type');
            foreach ($repositories as $id => $repository) {
                $directory = $root . '/repository_' . $repository->type;
                if (is_dir($directory)) {
                    fulldelete($directory);
                }
            }
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2016021500.0);
    }
    if ($oldversion < 2016021501.0) {
        // This could take a long time. Unfortunately, no way to know how long, and no way to do progress, so setting for 1 hour.
        upgrade_set_timeout(3600);
        // Define index userid-itemid (not unique) to be added to grade_grades_history.
        $table = new xmldb_table('grade_grades_history');
        $index = new xmldb_index('userid-itemid-timemodified', XMLDB_INDEX_NOTUNIQUE, array('userid', 'itemid', 'timemodified'));
        // Conditionally launch add index userid-itemid.
        if (!$dbman->index_exists($table, $index)) {
            $dbman->add_index($table, $index);
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2016021501.0);
    }
    return true;
}
Exemplo n.º 9
0
function xmldb_data_upgrade($oldversion) {
    global $CFG, $DB, $OUTPUT;

    $dbman = $DB->get_manager();

//===== 1.9.0 upgrade line ======//

    if ($oldversion < 2007101512) {
    /// Launch add field asearchtemplate again if does not exists yet - reported on several sites

        $table = new xmldb_table('data');
        $field = new xmldb_field('asearchtemplate', XMLDB_TYPE_TEXT, 'small', null, null, null, null, 'jstemplate');

        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        upgrade_mod_savepoint(true, 2007101512, 'data');
    }

    if ($oldversion < 2007101513) {
        // Upgrade all the data->notification currently being
        // NULL to 0
        $sql = "UPDATE {data} SET notification=0 WHERE notification IS NULL";
        $DB->execute($sql);

        $table = new xmldb_table('data');
        $field = new xmldb_field('notification', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'editany');
        // First step, Set NOT NULL
        $dbman->change_field_notnull($table, $field);
        // Second step, Set default to 0
        $dbman->change_field_default($table, $field);
        upgrade_mod_savepoint(true, 2007101513, 'data');
    }

    if ($oldversion < 2008081400) {
        $pattern = '/\#\#delete\#\#(\s+)\#\#approve\#\#/';
        $replacement = '##delete##$1##approve##$1##export##';
        $rs = $DB->get_recordset('data');
        foreach ($rs as $data) {
            $data->listtemplate = preg_replace($pattern, $replacement, $data->listtemplate);
            $data->singletemplate = preg_replace($pattern, $replacement, $data->singletemplate);
            $DB->update_record('data', $data);
        }
        $rs->close();

        upgrade_mod_savepoint(true, 2008081400, 'data');
    }

    if ($oldversion < 2008091400) {

        /////////////////////////////////////
        /// new file storage upgrade code ///
        /////////////////////////////////////

        $fs = get_file_storage();

        $empty = $DB->sql_empty(); // silly oracle empty string handling workaround

        $sqlfrom = "FROM {data_content} c
                    JOIN {data_fields} f     ON f.id = c.fieldid
                    JOIN {data_records} r    ON r.id = c.recordid
                    JOIN {data} d            ON d.id = r.dataid
                    JOIN {modules} m         ON m.name = 'data'
                    JOIN {course_modules} cm ON (cm.module = m.id AND cm.instance = d.id)
                   WHERE ".$DB->sql_compare_text('c.content', 2)." <> '$empty' AND c.content IS NOT NULL
                         AND (f.type = 'file' OR f.type = 'picture')";

        $count = $DB->count_records_sql("SELECT COUNT('x') $sqlfrom");

        $rs = $DB->get_recordset_sql("SELECT c.id, f.type, r.dataid, c.recordid, f.id AS fieldid, r.userid, c.content, c.content1, d.course, r.userid, cm.id AS cmid $sqlfrom ORDER BY d.course, d.id");

        if ($rs->valid()) {
            $pbar = new progress_bar('migratedatafiles', 500, true);

            $i = 0;
            foreach ($rs as $content) {
                $i++;
                upgrade_set_timeout(60); // set up timeout, may also abort execution
                $pbar->update($i, $count, "Migrating data entries - $i/$count.");

                $filepath = "$CFG->dataroot/$content->course/$CFG->moddata/data/$content->dataid/$content->fieldid/$content->recordid/$content->content";
                $context = get_context_instance(CONTEXT_MODULE, $content->cmid);

                if (!file_exists($filepath)) {
                    continue;
                }

                $filearea = 'content';
                $oldfilename = $content->content;
                $filename    = clean_param($oldfilename, PARAM_FILE);
                if ($filename === '') {
                    continue;
                }
                if (!$fs->file_exists($context->id, 'mod_data', $filearea, $content->id, '/', $filename)) {
                    $file_record = array('contextid'=>$context->id, 'component'=>'mod_data', 'filearea'=>$filearea, 'itemid'=>$content->id, 'filepath'=>'/', 'filename'=>$filename, 'userid'=>$content->userid);
                    if ($fs->create_file_from_pathname($file_record, $filepath)) {
                        unlink($filepath);
                        if ($oldfilename !== $filename) {
                            // update filename if needed
                            $DB->set_field('data_content', 'content', $filename, array('id'=>$content->id));
                        }
                        if ($content->type == 'picture') {
                            // migrate thumb
                            $filepath = "$CFG->dataroot/$content->course/$CFG->moddata/data/$content->dataid/$content->fieldid/$content->recordid/thumb/$content->content";
                            if (file_exists($filepath)) {
                                if (!$fs->file_exists($context->id, 'mod_data', $filearea, $content->id, '/', 'thumb_'.$filename)) {
                                    $file_record['filename'] = 'thumb_'.$file_record['filename'];
                                    $fs->create_file_from_pathname($file_record, $filepath);
                                }
                                unlink($filepath);
                            }
                        }
                    }
                }

                // remove dirs if empty
                @rmdir("$CFG->dataroot/$content->course/$CFG->moddata/data/$content->dataid/$content->fieldid/$content->recordid/thumb");
                @rmdir("$CFG->dataroot/$content->course/$CFG->moddata/data/$content->dataid/$content->fieldid/$content->recordid");
                @rmdir("$CFG->dataroot/$content->course/$CFG->moddata/data/$content->dataid/$content->fieldid");
                @rmdir("$CFG->dataroot/$content->course/$CFG->moddata/data/$content->dataid");
                @rmdir("$CFG->dataroot/$content->course/$CFG->moddata/data");
                @rmdir("$CFG->dataroot/$content->course/$CFG->moddata");
            }
        }
        $rs->close();

        upgrade_mod_savepoint(true, 2008091400, 'data');
    }

    if ($oldversion < 2008112700) {
        if (!get_config('data', 'requiredentriesfixflag')) {
            $databases = $DB->get_records_sql("SELECT d.*, c.fullname
                                                 FROM {data} d, {course} c
                                                WHERE d.course = c.id
                                                      AND (d.requiredentries > 0 OR d.requiredentriestoview > 0)
                                             ORDER BY c.fullname, d.name");
            if (!empty($databases)) {
                $a = new stdClass();
                $a->text = '';
                foreach($databases as $database) {
                    $a->text .= $database->fullname." - " .$database->name. " (course id: ".$database->course." - database id: ".$database->id.")<br/>";
                }
                //TODO: MDL-17427 send this info to "upgrade log" which will be implemented in 2.0
                echo $OUTPUT->notification(get_string('requiredentrieschanged', 'admin', $a));
            }
        }
        unset_config('requiredentriesfixflag', 'data'); // remove old flag
        upgrade_mod_savepoint(true, 2008112700, 'data');
    }

    if ($oldversion < 2009042000) {

    /// Define field introformat to be added to data
        $table = new xmldb_table('data');
        $field = new xmldb_field('introformat', XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'intro');

    /// Launch add field introformat
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }

        // conditionally migrate to html format in intro
        if ($CFG->texteditors !== 'textarea') {
            $rs = $DB->get_recordset('data', array('introformat'=>FORMAT_MOODLE), '', 'id,intro,introformat');
            foreach ($rs as $d) {
                $d->intro       = text_to_html($d->intro, false, false, true);
                $d->introformat = FORMAT_HTML;
                $DB->update_record('data', $d);
                upgrade_set_timeout();
            }
            $rs->close();
        }

    /// data savepoint reached
        upgrade_mod_savepoint(true, 2009042000, 'data');
    }

    if ($oldversion < 2009111701) {
        upgrade_set_timeout(60*20);

    /// Define table data_comments to be dropped
        $table = new xmldb_table('data_comments');

    /// Conditionally launch drop table for data_comments
        if ($dbman->table_exists($table)) {
            $sql = "SELECT d.id AS dataid,
                           d.course AS courseid,
                           c.userid,
                           r.id AS itemid,
                           c.id AS commentid,
                           c.content AS commentcontent,
                           c.format AS format,
                           c.created AS timecreated
                      FROM {data_comments} c, {data_records} r, {data} d
                     WHERE c.recordid=r.id AND r.dataid=d.id
                  ORDER BY dataid, courseid";
            /// move data comments to comments table
            $lastdataid = null;
            $lastcourseid = null;
            $modcontext = null;
            $rs = $DB->get_recordset_sql($sql);
            foreach($rs as $res) {
                if ($res->dataid != $lastdataid || $res->courseid != $lastcourseid) {
                    $cm = get_coursemodule_from_instance('data', $res->dataid, $res->courseid);
                    if ($cm) {
                        $modcontext = get_context_instance(CONTEXT_MODULE, $cm->id);
                    }
                    $lastdataid = $res->dataid;
                    $lastcourseid = $res->courseid;
                }
                $cmt = new stdClass();
                $cmt->contextid   = $modcontext->id;
                $cmt->commentarea = 'database_entry';
                $cmt->itemid      = $res->itemid;
                $cmt->content     = $res->commentcontent;
                $cmt->format      = $res->format;
                $cmt->userid      = $res->userid;
                $cmt->timecreated = $res->timecreated;
                // comments class will throw an exception if error occurs
                $cmt_id = $DB->insert_record('comments', $cmt);
                if (!empty($cmt_id)) {
                    $DB->delete_records('data_comments', array('id'=>$res->commentid));
                }
            }
            $rs->close();
            // the default exception handler will stop the script if error occurs before
            $dbman->drop_table($table);
        }

    /// data savepoint reached
        upgrade_mod_savepoint(true, 2009111701, 'data');
    }

    if ($oldversion < 2010031602) {
        //add assesstimestart and assesstimefinish columns to data
        $table = new xmldb_table('data');

        $field = new xmldb_field('assesstimestart');
        if (!$dbman->field_exists($table, $field)) {
            $field->set_attributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, 0, 'assessed');
            $dbman->add_field($table, $field);
        }

        $field = new xmldb_field('assesstimefinish');
        if (!$dbman->field_exists($table, $field)) {
            $field->set_attributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, 0, 'assesstimestart');
            $dbman->add_field($table, $field);
        }

        upgrade_mod_savepoint(true, 2010031602, 'data');
    }

    if ($oldversion < 2010042800) {
        //migrate data ratings to the central rating table
        $table = new xmldb_table('data_ratings');
        if ($dbman->table_exists($table)) {
            //data ratings didnt store time created and modified so Im using the times from the record the rating was attached to
            $sql = "INSERT INTO {rating} (contextid, scaleid, itemid, rating, userid, timecreated, timemodified)

                    SELECT cxt.id, d.scale, r.recordid AS itemid, r.rating, r.userid, re.timecreated AS timecreated, re.timemodified AS timemodified
                      FROM {data_ratings} r
                      JOIN {data_records} re ON r.recordid=re.id
                      JOIN {data} d ON d.id=re.dataid
                      JOIN {course_modules} cm ON cm.instance=d.id
                      JOIN {context} cxt ON cxt.instanceid=cm.id
                      JOIN {modules} m ON m.id=cm.module
                     WHERE m.name = :modname AND cxt.contextlevel = :contextlevel";
            $params['modname'] = 'data';
            $params['contextlevel'] = CONTEXT_MODULE;

            $DB->execute($sql, $params);

            //now drop data_ratings
            $dbman->drop_table($table);
        }

        upgrade_mod_savepoint(true, 2010042800, 'data');
    }

    //rerun the upgrade see MDL-24470
    if ($oldversion < 2010100101) {
        // Upgrade all the data->notification currently being
        // NULL to 0
        $sql = "UPDATE {data} SET notification=0 WHERE notification IS NULL";
        $DB->execute($sql);

        $table = new xmldb_table('data');
        $field = new xmldb_field('notification', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'editany');
        // First step, Set NOT NULL
        $dbman->change_field_notnull($table, $field);
        // Second step, Set default to 0
        $dbman->change_field_default($table, $field);
        upgrade_mod_savepoint(true, 2010100101, 'data');
    }

    if ($oldversion < 2011052300) {
        // rating.component and rating.ratingarea have now been added as mandatory fields.
        // Presently you can only rate data entries so component = 'mod_data' and ratingarea = 'entry'
        // for all ratings with a data context.
        // We want to update all ratings that belong to a data context and don't already have a
        // component set.
        // This could take a while reset upgrade timeout to 5 min
        upgrade_set_timeout(60 * 20);
        $sql = "UPDATE {rating}
                SET component = 'mod_data', ratingarea = 'entry'
                WHERE contextid IN (
                    SELECT ctx.id
                      FROM {context} ctx
                      JOIN {course_modules} cm ON cm.id = ctx.instanceid
                      JOIN {modules} m ON m.id = cm.module
                     WHERE ctx.contextlevel = 70 AND
                           m.name = 'data'
                ) AND component = 'unknown'";
        $DB->execute($sql);

        upgrade_mod_savepoint(true, 2011052300, 'data');
    }

    // Moodle v2.1.0 release upgrade line
    // Put any upgrade step following this

    // Moodle v2.2.0 release upgrade line
    // Put any upgrade step following this

    return true;
}
Exemplo n.º 10
0
/**
 * Moves all block attachments
 *
 * Unfortunately this function uses core file related functions - it might be necessary to tweak it if something changes there :-(
 */
function upgrade_migrate_files_blog()
{
    global $DB, $CFG;
    $fs = get_file_storage();
    $count = $DB->count_records_select('post', "module='blog' AND attachment IS NOT NULL AND attachment <> '1'");
    if ($rs = $DB->get_recordset_select('post', "module='blog' AND attachment IS NOT NULL AND attachment <> '1'")) {
        upgrade_set_timeout(60 * 20);
        // set up timeout, may also abort execution
        $pbar = new progress_bar('migrateblogfiles', 500, true);
        $i = 0;
        foreach ($rs as $entry) {
            $i++;
            $pathname = "{$CFG->dataroot}/blog/attachments/{$entry->id}/{$entry->attachment}";
            if (!file_exists($pathname)) {
                $entry->attachment = NULL;
                $DB->update_record('post', $entry);
                continue;
            }
            $filename = clean_param($entry->attachment, PARAM_FILE);
            if ($filename === '') {
                // weird file name, ignore it
                $entry->attachment = NULL;
                $DB->update_record('post', $entry);
                continue;
            }
            if (!is_readable($pathname)) {
                notify(" File not readable, skipping: " . $pathname);
                continue;
            }
            if (!$fs->file_exists(SYSCONTEXTID, 'blog', $entry->id, '/', $filename)) {
                $file_record = array('contextid' => SYSCONTEXTID, 'filearea' => 'blog', 'itemid' => $entry->id, 'filepath' => '/', 'filename' => $filename, 'timecreated' => filectime($pathname), 'timemodified' => filemtime($pathname), 'userid' => $entry->userid);
                $fs->create_file_from_pathname($file_record, $pathname);
            }
            @unlink($pathname);
            @rmdir("{$CFG->dataroot}/blog/attachments/{$entry->id}/");
            $entry->attachment = 1;
            // file name not needed there anymore
            $DB->update_record('post', $entry);
            $pbar->update($i, $count, "Migrated blog attachments - {$i}/{$count}.");
        }
        $rs->close();
    }
    @rmdir("{$CFG->dataroot}/blog/attachments/");
    @rmdir("{$CFG->dataroot}/blog/");
}
Exemplo n.º 11
0
/**
 * Main upgrade tasks to be executed on Moodle version bump
 *
 * This function is automatically executed after one bump in the Moodle core
 * version is detected. It's in charge of performing the required tasks
 * to raise core from the previous version to the next one.
 *
 * It's a collection of ordered blocks of code, named "upgrade steps",
 * each one performing one isolated (from the rest of steps) task. Usually
 * tasks involve creating new DB objects or performing manipulation of the
 * information for cleanup/fixup purposes.
 *
 * Each upgrade step has a fixed structure, that can be summarised as follows:
 *
 * if ($oldversion < XXXXXXXXXX.XX) {
 *     // Explanation of the update step, linking to issue in the Tracker if necessary
 *     upgrade_set_timeout(XX); // Optional for big tasks
 *     // Code to execute goes here, usually the XMLDB Editor will
 *     // help you here. See {@link http://docs.moodle.org/dev/XMLDB_editor}.
 *     upgrade_main_savepoint(true, XXXXXXXXXX.XX);
 * }
 *
 * All plugins within Moodle (modules, blocks, reports...) support the existence of
 * their own upgrade.php file, using the "Frankenstyle" component name as
 * defined at {@link http://docs.moodle.org/dev/Frankenstyle}, for example:
 *     - {@link xmldb_page_upgrade($oldversion)}. (modules don't require the plugintype ("mod_") to be used.
 *     - {@link xmldb_auth_manual_upgrade($oldversion)}.
 *     - {@link xmldb_workshopform_accumulative_upgrade($oldversion)}.
 *     - ....
 *
 * In order to keep the contents of this file reduced, it's allowed to create some helper
 * functions to be used here in the {@link upgradelib.php} file at the same directory. Note
 * that such a file must be manually included from upgrade.php, and there are some restrictions
 * about what can be used within it.
 *
 * For more information, take a look to the documentation available:
 *     - Data definition API: {@link http://docs.moodle.org/dev/Data_definition_API}
 *     - Upgrade API: {@link http://docs.moodle.org/dev/Upgrade_API}
 *
 * @param int $oldversion
 * @return bool always true
 */
function xmldb_main_upgrade($oldversion)
{
    global $CFG, $USER, $DB, $OUTPUT, $SITE;
    require_once $CFG->libdir . '/db/upgradelib.php';
    // Core Upgrade-related functions
    $dbman = $DB->get_manager();
    // loads ddl manager and xmldb classes
    if ($oldversion < 2011120500) {
        // just in case somebody hacks upgrade scripts or env, we really can not continue
        echo "You need to upgrade to 2.2.x first!\n";
        exit(1);
        // Note this savepoint is 100% unreachable, but needed to pass the upgrade checks
        upgrade_main_savepoint(true, 2011120500);
    }
    // Moodle v2.2.0 release upgrade line
    // Put any upgrade step following this
    if ($oldversion < 2011120500.02) {
        upgrade_set_timeout(60 * 20);
        // This may take a while
        // MDL-28180. Some missing restrictions in certain backup & restore operations
        // were causing incorrect duplicates in the course_completion_aggr_methd table.
        // This upgrade step takes rid of them.
        $sql = 'SELECT course, criteriatype, MIN(id) AS minid
                  FROM {course_completion_aggr_methd}
              GROUP BY course, criteriatype
                HAVING COUNT(*) > 1';
        $duprs = $DB->get_recordset_sql($sql);
        foreach ($duprs as $duprec) {
            // We need to handle NULLs in criteriatype diferently
            if (is_null($duprec->criteriatype)) {
                $where = 'course = ? AND criteriatype IS NULL AND id > ?';
                $params = array($duprec->course, $duprec->minid);
            } else {
                $where = 'course = ? AND criteriatype = ? AND id > ?';
                $params = array($duprec->course, $duprec->criteriatype, $duprec->minid);
            }
            $DB->delete_records_select('course_completion_aggr_methd', $where, $params);
        }
        $duprs->close();
        // Main savepoint reached
        upgrade_main_savepoint(true, 2011120500.02);
    }
    if ($oldversion < 2011120500.03) {
        // Changing precision of field value on table user_preferences to (1333)
        $table = new xmldb_table('user_preferences');
        $field = new xmldb_field('value', XMLDB_TYPE_CHAR, '1333', null, XMLDB_NOTNULL, null, null, 'name');
        // Launch change of precision for field value
        $dbman->change_field_precision($table, $field);
        // Main savepoint reached
        upgrade_main_savepoint(true, 2011120500.03);
    }
    if ($oldversion < 2012020200.03) {
        // Define index rolecontext (not unique) to be added to role_assignments
        $table = new xmldb_table('role_assignments');
        $index = new xmldb_index('rolecontext', XMLDB_INDEX_NOTUNIQUE, array('roleid', 'contextid'));
        // Conditionally launch add index rolecontext
        if (!$dbman->index_exists($table, $index)) {
            $dbman->add_index($table, $index);
        }
        // Define index usercontextrole (not unique) to be added to role_assignments
        $index = new xmldb_index('usercontextrole', XMLDB_INDEX_NOTUNIQUE, array('userid', 'contextid', 'roleid'));
        // Conditionally launch add index usercontextrole
        if (!$dbman->index_exists($table, $index)) {
            $dbman->add_index($table, $index);
        }
        // Main savepoint reached
        upgrade_main_savepoint(true, 2012020200.03);
    }
    if ($oldversion < 2012020200.06) {
        // Previously we always allowed users to override their email address via the messaging system
        // We have now added a setting to allow admins to turn this this ability on and off
        // While this setting defaults to 0 (off) we're setting it to 1 (on) to maintain the behaviour for upgrading sites
        set_config('messagingallowemailoverride', 1);
        // Main savepoint reached
        upgrade_main_savepoint(true, 2012020200.06);
    }
    if ($oldversion < 2012021700.01) {
        // Changing precision of field uniquehash on table post to 255
        $table = new xmldb_table('post');
        $field = new xmldb_field('uniquehash', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, 'content');
        // Launch change of precision for field uniquehash
        $dbman->change_field_precision($table, $field);
        // Main savepoint reached
        upgrade_main_savepoint(true, 2012021700.01);
    }
    if ($oldversion < 2012021700.02) {
        // Somewhere before 1.9 summary and content column in post table were not null. In 1.9+
        // not null became false.
        $columns = $DB->get_columns('post');
        // Fix discrepancies in summary field after upgrade from 1.9
        if (array_key_exists('summary', $columns) && $columns['summary']->not_null != false) {
            $table = new xmldb_table('post');
            $summaryfield = new xmldb_field('summary', XMLDB_TYPE_TEXT, 'big', null, null, null, null, 'subject');
            if ($dbman->field_exists($table, $summaryfield)) {
                $dbman->change_field_notnull($table, $summaryfield);
            }
        }
        // Fix discrepancies in content field after upgrade from 1.9
        if (array_key_exists('content', $columns) && $columns['content']->not_null != false) {
            $table = new xmldb_table('post');
            $contentfield = new xmldb_field('content', XMLDB_TYPE_TEXT, 'big', null, null, null, null, 'summary');
            if ($dbman->field_exists($table, $contentfield)) {
                $dbman->change_field_notnull($table, $contentfield);
            }
        }
        upgrade_main_savepoint(true, 2012021700.02);
    }
    // The ability to backup user (private) files is out completely - MDL-29248
    if ($oldversion < 2012030100.01) {
        unset_config('backup_general_user_files', 'backup');
        unset_config('backup_general_user_files_locked', 'backup');
        unset_config('backup_auto_user_files', 'backup');
        upgrade_main_savepoint(true, 2012030100.01);
    }
    if ($oldversion < 2012030100.02) {
        // migrate all numbers to signed - it should be safe to interrupt this and continue later
        upgrade_mysql_fix_unsigned_columns();
        // Main savepoint reached
        upgrade_main_savepoint(true, 2012030100.02);
    }
    if ($oldversion < 2012030900.01) {
        // migrate all texts and binaries to big size - it should be safe to interrupt this and continue later
        upgrade_mysql_fix_lob_columns();
        // Main savepoint reached
        upgrade_main_savepoint(true, 2012030900.01);
    }
    if ($oldversion < 2012031500.01) {
        // Upgrade old course_allowed_modules data to be permission overrides.
        if ($CFG->restrictmodulesfor === 'all') {
            $courses = $DB->get_records_menu('course', array(), 'id', 'id, 1');
        } else {
            if ($CFG->restrictmodulesfor === 'requested') {
                $courses = $DB->get_records_menu('course', array('retrictmodules' => 1), 'id', 'id, 1');
            } else {
                $courses = array();
            }
        }
        if (!$dbman->table_exists('course_allowed_modules')) {
            // Upgrade must already have been run on this server. This might happen,
            // for example, during development of these changes.
            $courses = array();
        }
        $modidtoname = $DB->get_records_menu('modules', array(), 'id', 'id, name');
        $coursecount = count($courses);
        if ($coursecount) {
            $pbar = new progress_bar('allowedmods', 500, true);
            $transaction = $DB->start_delegated_transaction();
        }
        $i = 0;
        foreach ($courses as $courseid => $notused) {
            $i += 1;
            upgrade_set_timeout(60);
            // 1 minute per course should be fine.
            $allowedmoduleids = $DB->get_records_menu('course_allowed_modules', array('course' => $courseid), 'module', 'module, 1');
            if (empty($allowedmoduleids)) {
                // This seems to be the best match for backwards compatibility,
                // not necessarily with the old code in course_allowed_module function,
                // but with the code that used to be in the coures settings form.
                $allowedmoduleids = explode(',', $CFG->defaultallowedmodules);
                $allowedmoduleids = array_combine($allowedmoduleids, $allowedmoduleids);
            }
            $context = context_course::instance($courseid);
            list($roleids) = get_roles_with_cap_in_context($context, 'moodle/course:manageactivities');
            list($managerroleids) = get_roles_with_cap_in_context($context, 'moodle/site:config');
            foreach ($managerroleids as $roleid) {
                unset($roleids[$roleid]);
            }
            foreach ($modidtoname as $modid => $modname) {
                if (isset($allowedmoduleids[$modid])) {
                    // Module is allowed, no worries.
                    continue;
                }
                $capability = 'mod/' . $modname . ':addinstance';
                foreach ($roleids as $roleid) {
                    assign_capability($capability, CAP_PREVENT, $roleid, $context);
                }
            }
            $pbar->update($i, $coursecount, "Upgrading legacy course_allowed_modules data - {$i}/{$coursecount}.");
        }
        if ($coursecount) {
            $transaction->allow_commit();
        }
        upgrade_main_savepoint(true, 2012031500.01);
    }
    if ($oldversion < 2012031500.02) {
        // Define field retrictmodules to be dropped from course
        $table = new xmldb_table('course');
        $field = new xmldb_field('restrictmodules');
        // Conditionally launch drop field requested
        if ($dbman->field_exists($table, $field)) {
            $dbman->drop_field($table, $field);
        }
        upgrade_main_savepoint(true, 2012031500.02);
    }
    if ($oldversion < 2012031500.03) {
        // Define table course_allowed_modules to be dropped
        $table = new xmldb_table('course_allowed_modules');
        // Conditionally launch drop table for course_allowed_modules
        if ($dbman->table_exists($table)) {
            $dbman->drop_table($table);
        }
        upgrade_main_savepoint(true, 2012031500.03);
    }
    if ($oldversion < 2012031500.04) {
        // Clean up the old admin settings.
        unset_config('restrictmodulesfor');
        unset_config('restrictbydefault');
        unset_config('defaultallowedmodules');
        upgrade_main_savepoint(true, 2012031500.04);
    }
    if ($oldversion < 2012032300.02) {
        // Migrate the old admin debug setting.
        if ($CFG->debug == 38911) {
            set_config('debug', DEBUG_DEVELOPER);
        } else {
            if ($CFG->debug == 6143) {
                set_config('debug', DEBUG_ALL);
            }
        }
        upgrade_main_savepoint(true, 2012032300.02);
    }
    if ($oldversion < 2012042300.0) {
        // This change makes the course_section index unique.
        // xmldb does not allow changing index uniqueness - instead we must drop
        // index then add it again
        $table = new xmldb_table('course_sections');
        $index = new xmldb_index('course_section', XMLDB_INDEX_NOTUNIQUE, array('course', 'section'));
        // Conditionally launch drop index course_section
        if ($dbman->index_exists($table, $index)) {
            $dbman->drop_index($table, $index);
        }
        // Look for any duplicate course_sections entries. There should not be
        // any but on some busy systems we found a few, maybe due to previous
        // bugs.
        $transaction = $DB->start_delegated_transaction();
        $rs = $DB->get_recordset_sql('
                SELECT DISTINCT
                    cs.id, cs.course
                FROM
                    {course_sections} cs
                    INNER JOIN {course_sections} older
                        ON cs.course = older.course AND cs.section = older.section
                        AND older.id < cs.id');
        foreach ($rs as $rec) {
            $DB->delete_records('course_sections', array('id' => $rec->id));
            // We can't use rebuild_course_cache() here because introducing sectioncache later
            // so reset modinfo manually.
            $DB->set_field('course', 'modinfo', null, array('id' => $rec->course));
        }
        $rs->close();
        $transaction->allow_commit();
        // Define index course_section (unique) to be added to course_sections
        $index = new xmldb_index('course_section', XMLDB_INDEX_UNIQUE, array('course', 'section'));
        // Conditionally launch add index course_section
        if (!$dbman->index_exists($table, $index)) {
            $dbman->add_index($table, $index);
        }
        // Main savepoint reached
        upgrade_main_savepoint(true, 2012042300.0);
    }
    if ($oldversion < 2012042300.02) {
        require_once $CFG->dirroot . '/completion/criteria/completion_criteria.php';
        // Delete orphaned criteria which were left when modules were removed
        if ($DB->get_dbfamily() === 'mysql') {
            $sql = "DELETE cc FROM {course_completion_criteria} cc\n                    LEFT JOIN {course_modules} cm ON cm.id = cc.moduleinstance\n                    WHERE cm.id IS NULL AND cc.criteriatype = " . COMPLETION_CRITERIA_TYPE_ACTIVITY;
        } else {
            $sql = "DELETE FROM {course_completion_criteria}\n                    WHERE NOT EXISTS (\n                        SELECT 'x' FROM {course_modules}\n                        WHERE {course_modules}.id = {course_completion_criteria}.moduleinstance)\n                    AND {course_completion_criteria}.criteriatype = " . COMPLETION_CRITERIA_TYPE_ACTIVITY;
        }
        $DB->execute($sql);
        // Main savepoint reached
        upgrade_main_savepoint(true, 2012042300.02);
    }
    if ($oldversion < 2012050300.01) {
        // Make sure deleted users do not have picture flag.
        $DB->set_field('user', 'picture', 0, array('deleted' => 1, 'picture' => 1));
        upgrade_main_savepoint(true, 2012050300.01);
    }
    if ($oldversion < 2012050300.02) {
        // Changing precision of field picture on table user to (10)
        $table = new xmldb_table('user');
        $field = new xmldb_field('picture', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0', 'secret');
        // Launch change of precision for field picture
        $dbman->change_field_precision($table, $field);
        // Main savepoint reached
        upgrade_main_savepoint(true, 2012050300.02);
    }
    if ($oldversion < 2012050300.03) {
        // Define field coursedisplay to be added to course
        $table = new xmldb_table('course');
        $field = new xmldb_field('coursedisplay', XMLDB_TYPE_INTEGER, '2', null, XMLDB_NOTNULL, null, '0', 'completionnotify');
        // Conditionally launch add field coursedisplay
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        // Main savepoint reached
        upgrade_main_savepoint(true, 2012050300.03);
    }
    if ($oldversion < 2012050300.04) {
        // Define table course_display to be dropped
        $table = new xmldb_table('course_display');
        // Conditionally launch drop table for course_display
        if ($dbman->table_exists($table)) {
            $dbman->drop_table($table);
        }
        // Main savepoint reached
        upgrade_main_savepoint(true, 2012050300.04);
    }
    if ($oldversion < 2012050300.05) {
        // Clean up removed admin setting.
        unset_config('navlinkcoursesections');
        upgrade_main_savepoint(true, 2012050300.05);
    }
    if ($oldversion < 2012050400.01) {
        // Define index sortorder (not unique) to be added to course
        $table = new xmldb_table('course');
        $index = new xmldb_index('sortorder', XMLDB_INDEX_NOTUNIQUE, array('sortorder'));
        // Conditionally launch add index sortorder
        if (!$dbman->index_exists($table, $index)) {
            $dbman->add_index($table, $index);
        }
        // Main savepoint reached
        upgrade_main_savepoint(true, 2012050400.01);
    }
    if ($oldversion < 2012050400.02) {
        // Clean up removed admin setting.
        unset_config('enablecourseajax');
        upgrade_main_savepoint(true, 2012050400.02);
    }
    if ($oldversion < 2012051100.01) {
        // Define field idnumber to be added to groups
        $table = new xmldb_table('groups');
        $field = new xmldb_field('idnumber', XMLDB_TYPE_CHAR, '100', null, XMLDB_NOTNULL, null, null, 'courseid');
        $index = new xmldb_index('idnumber', XMLDB_INDEX_NOTUNIQUE, array('idnumber'));
        // Conditionally launch add field idnumber
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        // Conditionally launch add index idnumber
        if (!$dbman->index_exists($table, $index)) {
            $dbman->add_index($table, $index);
        }
        // Define field idnumber to be added to groupings
        $table = new xmldb_table('groupings');
        $field = new xmldb_field('idnumber', XMLDB_TYPE_CHAR, '100', null, XMLDB_NOTNULL, null, null, 'name');
        $index = new xmldb_index('idnumber', XMLDB_INDEX_NOTUNIQUE, array('idnumber'));
        // Conditionally launch add field idnumber
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        // Conditionally launch add index idnumber
        if (!$dbman->index_exists($table, $index)) {
            $dbman->add_index($table, $index);
        }
        // Main savepoint reached
        upgrade_main_savepoint(true, 2012051100.01);
    }
    if ($oldversion < 2012051100.03) {
        // Amend course table to add sectioncache cache
        $table = new xmldb_table('course');
        $field = new xmldb_field('sectioncache', XMLDB_TYPE_TEXT, null, null, null, null, null, 'showgrades');
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        // Amend course_sections to add date, time and groupingid availability
        // conditions and a setting about whether to show them
        $table = new xmldb_table('course_sections');
        $field = new xmldb_field('availablefrom', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0', 'visible');
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        $field = new xmldb_field('availableuntil', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0', 'availablefrom');
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        $field = new xmldb_field('showavailability', XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, '0', 'availableuntil');
        // Conditionally launch add field showavailability
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        $field = new xmldb_field('groupingid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0', 'showavailability');
        // Conditionally launch add field groupingid
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        // Add course_sections_availability to add completion & grade availability conditions
        $table = new xmldb_table('course_sections_availability');
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
        $table->add_field('coursesectionid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null);
        $table->add_field('sourcecmid', XMLDB_TYPE_INTEGER, '10', null, null, null, null);
        $table->add_field('requiredcompletion', XMLDB_TYPE_INTEGER, '1', null, null, null, null);
        $table->add_field('gradeitemid', XMLDB_TYPE_INTEGER, '10', null, null, null, null);
        $table->add_field('grademin', XMLDB_TYPE_NUMBER, '10, 5', null, null, null, null);
        $table->add_field('grademax', XMLDB_TYPE_NUMBER, '10, 5', null, null, null, null);
        $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->add_key('coursesectionid', XMLDB_KEY_FOREIGN, array('coursesectionid'), 'course_sections', array('id'));
        $table->add_key('sourcecmid', XMLDB_KEY_FOREIGN, array('sourcecmid'), 'course_modules', array('id'));
        $table->add_key('gradeitemid', XMLDB_KEY_FOREIGN, array('gradeitemid'), 'grade_items', array('id'));
        if (!$dbman->table_exists($table)) {
            $dbman->create_table($table);
        }
        // Main savepoint reached
        upgrade_main_savepoint(true, 2012051100.03);
    }
    if ($oldversion < 2012052100.0) {
        // Define field referencefileid to be added to files.
        $table = new xmldb_table('files');
        // Define field referencefileid to be added to files.
        $field = new xmldb_field('referencefileid', XMLDB_TYPE_INTEGER, '10', null, null, null, null, 'sortorder');
        // Conditionally launch add field referencefileid.
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        // Define field referencelastsync to be added to files.
        $field = new xmldb_field('referencelastsync', XMLDB_TYPE_INTEGER, '10', null, null, null, null, 'referencefileid');
        // Conditionally launch add field referencelastsync.
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        // Define field referencelifetime to be added to files.
        $field = new xmldb_field('referencelifetime', XMLDB_TYPE_INTEGER, '10', null, null, null, null, 'referencelastsync');
        // Conditionally launch add field referencelifetime.
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        $key = new xmldb_key('referencefileid', XMLDB_KEY_FOREIGN, array('referencefileid'), 'files_reference', array('id'));
        // Launch add key referencefileid
        $dbman->add_key($table, $key);
        // Define table files_reference to be created.
        $table = new xmldb_table('files_reference');
        // Adding fields to table files_reference.
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
        $table->add_field('repositoryid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null);
        $table->add_field('lastsync', XMLDB_TYPE_INTEGER, '10', null, null, null, null);
        $table->add_field('lifetime', XMLDB_TYPE_INTEGER, '10', null, null, null, null);
        $table->add_field('reference', XMLDB_TYPE_TEXT, null, null, null, null, null);
        // Adding keys to table files_reference.
        $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->add_key('repositoryid', XMLDB_KEY_FOREIGN, array('repositoryid'), 'repository_instances', array('id'));
        // Conditionally launch create table for files_reference
        if (!$dbman->table_exists($table)) {
            $dbman->create_table($table);
        }
        // Main savepoint reached
        upgrade_main_savepoint(true, 2012052100.0);
    }
    if ($oldversion < 2012052500.03) {
        // fix invalid course_completion_records MDL-27368
        //first get all instances of duplicate records
        $sql = 'SELECT userid, course FROM {course_completions} WHERE (deleted IS NULL OR deleted <> 1) GROUP BY userid, course HAVING (count(id) > 1)';
        $duplicates = $DB->get_recordset_sql($sql, array());
        foreach ($duplicates as $duplicate) {
            $pointer = 0;
            //now get all the records for this user/course
            $sql = 'userid = ? AND course = ? AND (deleted IS NULL OR deleted <> 1)';
            $completions = $DB->get_records_select('course_completions', $sql, array($duplicate->userid, $duplicate->course), 'timecompleted DESC, timestarted DESC');
            $needsupdate = false;
            $origcompletion = null;
            foreach ($completions as $completion) {
                $pointer++;
                if ($pointer === 1) {
                    //keep 1st record but delete all others.
                    $origcompletion = $completion;
                } else {
                    //we need to keep the "oldest" of all these fields as the valid completion record.
                    $fieldstocheck = array('timecompleted', 'timestarted', 'timeenrolled');
                    foreach ($fieldstocheck as $f) {
                        if ($origcompletion->{$f} > $completion->{$f}) {
                            $origcompletion->{$f} = $completion->{$f};
                            $needsupdate = true;
                        }
                    }
                    $DB->delete_records('course_completions', array('id' => $completion->id));
                }
            }
            if ($needsupdate) {
                $DB->update_record('course_completions', $origcompletion);
            }
        }
        // Main savepoint reached
        upgrade_main_savepoint(true, 2012052500.03);
    }
    if ($oldversion < 2012052900.0) {
        // Clean up all duplicate records in the course_completions table in preparation
        // for adding a new index there.
        upgrade_course_completion_remove_duplicates('course_completions', array('userid', 'course'), array('timecompleted', 'timestarted', 'timeenrolled'));
        // Main savepoint reached
        upgrade_main_savepoint(true, 2012052900.0);
    }
    if ($oldversion < 2012052900.01) {
        // Add indexes to prevent new duplicates in the course_completions table.
        // Define index useridcourse (unique) to be added to course_completions
        $table = new xmldb_table('course_completions');
        $index = new xmldb_index('useridcourse', XMLDB_INDEX_UNIQUE, array('userid', 'course'));
        // Conditionally launch add index useridcourse
        if (!$dbman->index_exists($table, $index)) {
            $dbman->add_index($table, $index);
        }
        // Main savepoint reached
        upgrade_main_savepoint(true, 2012052900.01);
    }
    if ($oldversion < 2012052900.02) {
        // Clean up all duplicate records in the course_completion_crit_compl table in preparation
        // for adding a new index there.
        upgrade_course_completion_remove_duplicates('course_completion_crit_compl', array('userid', 'course', 'criteriaid'), array('timecompleted'));
        // Main savepoint reached
        upgrade_main_savepoint(true, 2012052900.02);
    }
    if ($oldversion < 2012052900.03) {
        // Add indexes to prevent new duplicates in the course_completion_crit_compl table.
        // Define index useridcoursecriteraid (unique) to be added to course_completion_crit_compl
        $table = new xmldb_table('course_completion_crit_compl');
        $index = new xmldb_index('useridcoursecriteraid', XMLDB_INDEX_UNIQUE, array('userid', 'course', 'criteriaid'));
        // Conditionally launch add index useridcoursecriteraid
        if (!$dbman->index_exists($table, $index)) {
            $dbman->add_index($table, $index);
        }
        // Main savepoint reached
        upgrade_main_savepoint(true, 2012052900.03);
    }
    if ($oldversion < 2012052900.04) {
        // Clean up all duplicate records in the course_completion_aggr_methd table in preparation
        // for adding a new index there.
        upgrade_course_completion_remove_duplicates('course_completion_aggr_methd', array('course', 'criteriatype'));
        // Main savepoint reached
        upgrade_main_savepoint(true, 2012052900.04);
    }
    if ($oldversion < 2012052900.05) {
        // Add indexes to prevent new duplicates in the course_completion_aggr_methd table.
        // Define index coursecriteratype (unique) to be added to course_completion_aggr_methd
        $table = new xmldb_table('course_completion_aggr_methd');
        $index = new xmldb_index('coursecriteriatype', XMLDB_INDEX_UNIQUE, array('course', 'criteriatype'));
        // Conditionally launch add index coursecriteratype
        if (!$dbman->index_exists($table, $index)) {
            $dbman->add_index($table, $index);
        }
        // Main savepoint reached
        upgrade_main_savepoint(true, 2012052900.05);
    }
    if ($oldversion < 2012060600.01) {
        // Add field referencehash to files_reference
        $table = new xmldb_table('files_reference');
        $field = new xmldb_field('referencehash', XMLDB_TYPE_CHAR, '40', null, XMLDB_NOTNULL, null, null, 'reference');
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        upgrade_main_savepoint(true, 2012060600.01);
    }
    if ($oldversion < 2012060600.02) {
        // Populate referencehash field with SHA1 hash of the reference - this shoudl affect only 2.3dev sites
        // that were using the feature for testing. Production sites have the table empty.
        $rs = $DB->get_recordset('files_reference', null, '', 'id, reference');
        foreach ($rs as $record) {
            $hash = sha1($record->reference);
            $DB->set_field('files_reference', 'referencehash', $hash, array('id' => $record->id));
        }
        $rs->close();
        upgrade_main_savepoint(true, 2012060600.02);
    }
    if ($oldversion < 2012060600.03) {
        // Merge duplicate records in files_reference that were created during the development
        // phase at 2.3dev sites. This is needed so we can create the unique index over
        // (repositoryid, referencehash) fields.
        $sql = "SELECT repositoryid, referencehash, MIN(id) AS minid\n                  FROM {files_reference}\n              GROUP BY repositoryid, referencehash\n                HAVING COUNT(*) > 1";
        $duprs = $DB->get_recordset_sql($sql);
        foreach ($duprs as $duprec) {
            // get the list of all ids in {files_reference} that need to be remapped
            $dupids = $DB->get_records_select('files_reference', "repositoryid = ? AND referencehash = ? AND id > ?", array($duprec->repositoryid, $duprec->referencehash, $duprec->minid), '', 'id');
            $dupids = array_keys($dupids);
            // relink records in {files} that are now referring to a duplicate record
            // in {files_reference} to refer to the first one
            list($subsql, $subparams) = $DB->get_in_or_equal($dupids);
            $DB->set_field_select('files', 'referencefileid', $duprec->minid, "referencefileid {$subsql}", $subparams);
            // and finally remove all orphaned records from {files_reference}
            $DB->delete_records_list('files_reference', 'id', $dupids);
        }
        $duprs->close();
        upgrade_main_savepoint(true, 2012060600.03);
    }
    if ($oldversion < 2012060600.04) {
        // Add a unique index over repositoryid and referencehash fields in files_reference table
        $table = new xmldb_table('files_reference');
        $index = new xmldb_index('uq_external_file', XMLDB_INDEX_UNIQUE, array('repositoryid', 'referencehash'));
        if (!$dbman->index_exists($table, $index)) {
            $dbman->add_index($table, $index);
        }
        upgrade_main_savepoint(true, 2012060600.04);
    }
    if ($oldversion < 2012061800.01) {
        // Define field screenreader to be dropped from user
        $table = new xmldb_table('user');
        $field = new xmldb_field('ajax');
        // Conditionally launch drop field screenreader
        if ($dbman->field_exists($table, $field)) {
            $dbman->drop_field($table, $field);
        }
        // Main savepoint reached
        upgrade_main_savepoint(true, 2012061800.01);
    }
    if ($oldversion < 2012062000.0) {
        // Add field newcontextid to backup_files_template
        $table = new xmldb_table('backup_files_template');
        $field = new xmldb_field('newcontextid', XMLDB_TYPE_INTEGER, '10', null, null, null, null, 'info');
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        upgrade_main_savepoint(true, 2012062000.0);
    }
    if ($oldversion < 2012062000.01) {
        // Add field newitemid to backup_files_template
        $table = new xmldb_table('backup_files_template');
        $field = new xmldb_field('newitemid', XMLDB_TYPE_INTEGER, '10', null, null, null, null, 'newcontextid');
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        upgrade_main_savepoint(true, 2012062000.01);
    }
    // Moodle v2.3.0 release upgrade line
    // Put any upgrade step following this
    if ($oldversion < 2012062500.02) {
        // Drop some old backup tables, not used anymore
        // Define table backup_files to be dropped
        $table = new xmldb_table('backup_files');
        // Conditionally launch drop table for backup_files
        if ($dbman->table_exists($table)) {
            $dbman->drop_table($table);
        }
        // Define table backup_ids to be dropped
        $table = new xmldb_table('backup_ids');
        // Conditionally launch drop table for backup_ids
        if ($dbman->table_exists($table)) {
            $dbman->drop_table($table);
        }
        // Main savepoint reached
        upgrade_main_savepoint(true, 2012062500.02);
    }
    if ($oldversion < 2012070600.04) {
        // Define table course_modules_avail_fields to be created
        $table = new xmldb_table('course_modules_avail_fields');
        // Adding fields to table course_modules_avail_fields
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
        $table->add_field('coursemoduleid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null);
        $table->add_field('userfield', XMLDB_TYPE_CHAR, '50', null, null, null, null);
        $table->add_field('customfieldid', XMLDB_TYPE_INTEGER, '10', null, null, null, null);
        $table->add_field('operator', XMLDB_TYPE_CHAR, '20', null, XMLDB_NOTNULL, null, null);
        $table->add_field('value', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null);
        // Adding keys to table course_modules_avail_fields
        $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->add_key('coursemoduleid', XMLDB_KEY_FOREIGN, array('coursemoduleid'), 'course_modules', array('id'));
        // Conditionally launch create table for course_modules_avail_fields
        if (!$dbman->table_exists($table)) {
            $dbman->create_table($table);
        }
        // Main savepoint reached
        upgrade_main_savepoint(true, 2012070600.04);
    }
    if ($oldversion < 2012070600.05) {
        // Define table course_sections_avail_fields to be created
        $table = new xmldb_table('course_sections_avail_fields');
        // Adding fields to table course_sections_avail_fields
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
        $table->add_field('coursesectionid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null);
        $table->add_field('userfield', XMLDB_TYPE_CHAR, '50', null, null, null, null);
        $table->add_field('customfieldid', XMLDB_TYPE_INTEGER, '10', null, null, null, null);
        $table->add_field('operator', XMLDB_TYPE_CHAR, '20', null, XMLDB_NOTNULL, null, null);
        $table->add_field('value', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null);
        // Adding keys to table course_sections_avail_fields
        $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->add_key('coursesectionid', XMLDB_KEY_FOREIGN, array('coursesectionid'), 'course_sections', array('id'));
        // Conditionally launch create table for course_sections_avail_fields
        if (!$dbman->table_exists($table)) {
            $dbman->create_table($table);
        }
        // Main savepoint reached
        upgrade_main_savepoint(true, 2012070600.05);
    }
    if ($oldversion < 2012070600.06) {
        // Drop "deleted" fields
        $table = new xmldb_table('course_completions');
        $field = new xmldb_field('timenotified');
        $field = new xmldb_field('deleted');
        // Conditionally launch drop field deleted from course_completions
        if ($dbman->field_exists($table, $field)) {
            $dbman->drop_field($table, $field);
        }
        $field = new xmldb_field('timenotified');
        // Conditionally launch drop field timenotified from course_completions
        if ($dbman->field_exists($table, $field)) {
            $dbman->drop_field($table, $field);
        }
        // Main savepoint reached
        upgrade_main_savepoint(true, 2012070600.06);
    }
    if ($oldversion < 2012070600.07) {
        $table = new xmldb_table('course_completion_crit_compl');
        $field = new xmldb_field('deleted');
        // Conditionally launch drop field deleted from course_completion_crit_compl
        if ($dbman->field_exists($table, $field)) {
            $dbman->drop_field($table, $field);
        }
        // Main savepoint reached
        upgrade_main_savepoint(true, 2012070600.07);
    }
    if ($oldversion < 2012070600.08) {
        // Drop unused table "course_completion_notify"
        $table = new xmldb_table('course_completion_notify');
        // Conditionally launch drop table course_completion_notify
        if ($dbman->table_exists($table)) {
            $dbman->drop_table($table);
        }
        // Main savepoint reached
        upgrade_main_savepoint(true, 2012070600.08);
    }
    if ($oldversion < 2012070600.09) {
        // Define index path (not unique) to be added to context
        $table = new xmldb_table('context');
        $index = new xmldb_index('path', XMLDB_INDEX_NOTUNIQUE, array('path'), array('varchar_pattern_ops'));
        // Recreate index with new pattern hint
        if ($DB->get_dbfamily() === 'postgres') {
            if ($dbman->index_exists($table, $index)) {
                $dbman->drop_index($table, $index);
            }
            $dbman->add_index($table, $index);
        }
        // Main savepoint reached
        upgrade_main_savepoint(true, 2012070600.09);
    }
    if ($oldversion < 2012070600.1) {
        // Define index name (unique) to be dropped form role
        $table = new xmldb_table('role');
        $index = new xmldb_index('name', XMLDB_INDEX_UNIQUE, array('name'));
        // Conditionally launch drop index name
        if ($dbman->index_exists($table, $index)) {
            $dbman->drop_index($table, $index);
        }
        // Main savepoint reached
        upgrade_main_savepoint(true, 2012070600.1);
    }
    if ($oldversion < 2012070600.11) {
        // Define index component-itemid-userid (not unique) to be added to role_assignments
        $table = new xmldb_table('role_assignments');
        $index = new xmldb_index('component-itemid-userid', XMLDB_INDEX_NOTUNIQUE, array('component', 'itemid', 'userid'));
        // Conditionally launch add index component-itemid-userid
        if (!$dbman->index_exists($table, $index)) {
            $dbman->add_index($table, $index);
        }
        // Main savepoint reached
        upgrade_main_savepoint(true, 2012070600.11);
    }
    if ($oldversion < 2012071900.01) {
        // Cleanup after simpeltests tool
        capabilities_cleanup('tool_unittest');
        unset_all_config_for_plugin('tool_unittest');
        upgrade_main_savepoint(true, 2012071900.01);
    }
    if ($oldversion < 2012072400.0) {
        // Remove obsolete xhtml strict setting - use THEME->doctype in theme config if necessary,
        // see theme_config->doctype in lib/outputlib.php for more details.
        unset_config('xmlstrictheaders');
        upgrade_main_savepoint(true, 2012072400.0);
    }
    if ($oldversion < 2012072401.0) {
        // Saves orphaned questions from the Dark Side
        upgrade_save_orphaned_questions();
        // Main savepoint reached
        upgrade_main_savepoint(true, 2012072401.0);
    }
    if ($oldversion < 2012072600.01) {
        // Handle events with empty eventtype //MDL-32827
        $DB->set_field('event', 'eventtype', 'site', array('eventtype' => '', 'courseid' => $SITE->id));
        $DB->set_field_select('event', 'eventtype', 'due', "eventtype = '' AND courseid != 0 AND groupid = 0 AND (modulename = 'assignment' OR modulename = 'assign')");
        $DB->set_field_select('event', 'eventtype', 'course', "eventtype = '' AND courseid != 0 AND groupid = 0");
        $DB->set_field_select('event', 'eventtype', 'group', "eventtype = '' AND groupid != 0");
        $DB->set_field_select('event', 'eventtype', 'user', "eventtype = '' AND userid != 0");
        // Main savepoint reached
        upgrade_main_savepoint(true, 2012072600.01);
    }
    if ($oldversion < 2012080200.02) {
        // Drop obsolete question upgrade field that should have been added to the install.xml.
        $table = new xmldb_table('question');
        $field = new xmldb_field('oldquestiontextformat', XMLDB_TYPE_INTEGER, '2', null, XMLDB_NOTNULL, null, '0');
        if ($dbman->field_exists($table, $field)) {
            $dbman->drop_field($table, $field);
        }
        upgrade_main_savepoint(true, 2012080200.02);
    }
    if ($oldversion < 2012081400.01) {
        // Move the ability to disable blogs to its own setting MDL-25012.
        if (isset($CFG->bloglevel)) {
            // Only change settings if existing setting was set.
            if (empty($CFG->bloglevel)) {
                set_config('enableblogs', 0);
                // Now set the bloglevel to a valid setting as the disabled setting has been removed.
                // This prevents confusing results when users enable the blog system in future.
                set_config('bloglevel', BLOG_USER_LEVEL);
            } else {
                set_config('enableblogs', 1);
            }
        }
        // Main savepoint reached
        upgrade_main_savepoint(true, 2012081400.01);
    }
    return true;
}
Exemplo n.º 12
0
/**
 * Main upgrade tasks to be executed on Moodle version bump
 *
 * This function is automatically executed after one bump in the Moodle core
 * version is detected. It's in charge of performing the required tasks
 * to raise core from the previous version to the next one.
 *
 * It's a collection of ordered blocks of code, named "upgrade steps",
 * each one performing one isolated (from the rest of steps) task. Usually
 * tasks involve creating new DB objects or performing manipulation of the
 * information for cleanup/fixup purposes.
 *
 * Each upgrade step has a fixed structure, that can be summarised as follows:
 *
 * if ($oldversion < XXXXXXXXXX.XX) {
 *     // Explanation of the update step, linking to issue in the Tracker if necessary
 *     upgrade_set_timeout(XX); // Optional for big tasks
 *     // Code to execute goes here, usually the XMLDB Editor will
 *     // help you here. See {@link http://docs.moodle.org/dev/XMLDB_editor}.
 *     upgrade_main_savepoint(true, XXXXXXXXXX.XX);
 * }
 *
 * All plugins within Moodle (modules, blocks, reports...) support the existence of
 * their own upgrade.php file, using the "Frankenstyle" component name as
 * defined at {@link http://docs.moodle.org/dev/Frankenstyle}, for example:
 *     - {@link xmldb_page_upgrade($oldversion)}. (modules don't require the plugintype ("mod_") to be used.
 *     - {@link xmldb_auth_manual_upgrade($oldversion)}.
 *     - {@link xmldb_workshopform_accumulative_upgrade($oldversion)}.
 *     - ....
 *
 * In order to keep the contents of this file reduced, it's allowed to create some helper
 * functions to be used here in the {@link upgradelib.php} file at the same directory. Note
 * that such a file must be manually included from upgrade.php, and there are some restrictions
 * about what can be used within it.
 *
 * For more information, take a look to the documentation available:
 *     - Data definition API: {@link http://docs.moodle.org/dev/Data_definition_API}
 *     - Upgrade API: {@link http://docs.moodle.org/dev/Upgrade_API}
 *
 * @param int $oldversion
 * @return bool always true
 */
function xmldb_main_upgrade($oldversion)
{
    global $CFG, $USER, $DB, $OUTPUT, $SITE, $COURSE;
    require_once $CFG->libdir . '/db/upgradelib.php';
    // Core Upgrade-related functions
    $dbman = $DB->get_manager();
    // loads ddl manager and xmldb classes
    if ($oldversion < 2011120500) {
        // just in case somebody hacks upgrade scripts or env, we really can not continue
        echo "You need to upgrade to 2.2.x first!\n";
        exit(1);
        // Note this savepoint is 100% unreachable, but needed to pass the upgrade checks
        upgrade_main_savepoint(true, 2011120500);
    }
    // Moodle v2.2.0 release upgrade line
    // Put any upgrade step following this
    if ($oldversion < 2011120500.02) {
        upgrade_set_timeout(60 * 20);
        // This may take a while
        // MDL-28180. Some missing restrictions in certain backup & restore operations
        // were causing incorrect duplicates in the course_completion_aggr_methd table.
        // This upgrade step takes rid of them.
        $sql = 'SELECT course, criteriatype, MIN(id) AS minid
                  FROM {course_completion_aggr_methd}
              GROUP BY course, criteriatype
                HAVING COUNT(*) > 1';
        $duprs = $DB->get_recordset_sql($sql);
        foreach ($duprs as $duprec) {
            // We need to handle NULLs in criteriatype diferently
            if (is_null($duprec->criteriatype)) {
                $where = 'course = ? AND criteriatype IS NULL AND id > ?';
                $params = array($duprec->course, $duprec->minid);
            } else {
                $where = 'course = ? AND criteriatype = ? AND id > ?';
                $params = array($duprec->course, $duprec->criteriatype, $duprec->minid);
            }
            $DB->delete_records_select('course_completion_aggr_methd', $where, $params);
        }
        $duprs->close();
        // Main savepoint reached
        upgrade_main_savepoint(true, 2011120500.02);
    }
    if ($oldversion < 2011120500.03) {
        // Changing precision of field value on table user_preferences to (1333)
        $table = new xmldb_table('user_preferences');
        $field = new xmldb_field('value', XMLDB_TYPE_CHAR, '1333', null, XMLDB_NOTNULL, null, null, 'name');
        // Launch change of precision for field value
        $dbman->change_field_precision($table, $field);
        // Main savepoint reached
        upgrade_main_savepoint(true, 2011120500.03);
    }
    if ($oldversion < 2012020200.03) {
        // Define index rolecontext (not unique) to be added to role_assignments
        $table = new xmldb_table('role_assignments');
        $index = new xmldb_index('rolecontext', XMLDB_INDEX_NOTUNIQUE, array('roleid', 'contextid'));
        // Conditionally launch add index rolecontext
        if (!$dbman->index_exists($table, $index)) {
            $dbman->add_index($table, $index);
        }
        // Define index usercontextrole (not unique) to be added to role_assignments
        $index = new xmldb_index('usercontextrole', XMLDB_INDEX_NOTUNIQUE, array('userid', 'contextid', 'roleid'));
        // Conditionally launch add index usercontextrole
        if (!$dbman->index_exists($table, $index)) {
            $dbman->add_index($table, $index);
        }
        // Main savepoint reached
        upgrade_main_savepoint(true, 2012020200.03);
    }
    if ($oldversion < 2012020200.06) {
        // Previously we always allowed users to override their email address via the messaging system
        // We have now added a setting to allow admins to turn this this ability on and off
        // While this setting defaults to 0 (off) we're setting it to 1 (on) to maintain the behaviour for upgrading sites
        set_config('messagingallowemailoverride', 1);
        // Main savepoint reached
        upgrade_main_savepoint(true, 2012020200.06);
    }
    if ($oldversion < 2012021700.01) {
        // Changing precision of field uniquehash on table post to 255
        $table = new xmldb_table('post');
        $field = new xmldb_field('uniquehash', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, 'content');
        // Launch change of precision for field uniquehash
        $dbman->change_field_precision($table, $field);
        // Main savepoint reached
        upgrade_main_savepoint(true, 2012021700.01);
    }
    if ($oldversion < 2012021700.02) {
        // Somewhere before 1.9 summary and content column in post table were not null. In 1.9+
        // not null became false.
        $columns = $DB->get_columns('post');
        // Fix discrepancies in summary field after upgrade from 1.9
        if (array_key_exists('summary', $columns) && $columns['summary']->not_null != false) {
            $table = new xmldb_table('post');
            $summaryfield = new xmldb_field('summary', XMLDB_TYPE_TEXT, 'big', null, null, null, null, 'subject');
            if ($dbman->field_exists($table, $summaryfield)) {
                $dbman->change_field_notnull($table, $summaryfield);
            }
        }
        // Fix discrepancies in content field after upgrade from 1.9
        if (array_key_exists('content', $columns) && $columns['content']->not_null != false) {
            $table = new xmldb_table('post');
            $contentfield = new xmldb_field('content', XMLDB_TYPE_TEXT, 'big', null, null, null, null, 'summary');
            if ($dbman->field_exists($table, $contentfield)) {
                $dbman->change_field_notnull($table, $contentfield);
            }
        }
        upgrade_main_savepoint(true, 2012021700.02);
    }
    // The ability to backup user (private) files is out completely - MDL-29248
    if ($oldversion < 2012030100.01) {
        unset_config('backup_general_user_files', 'backup');
        unset_config('backup_general_user_files_locked', 'backup');
        unset_config('backup_auto_user_files', 'backup');
        upgrade_main_savepoint(true, 2012030100.01);
    }
    if ($oldversion < 2012030900.01) {
        // Migrate all numbers to signed & all texts and binaries to big size.
        // It should be safe to interrupt this and continue later.
        upgrade_mysql_fix_unsigned_and_lob_columns();
        // Main savepoint reached
        upgrade_main_savepoint(true, 2012030900.01);
    }
    if ($oldversion < 2012031500.01) {
        // Upgrade old course_allowed_modules data to be permission overrides.
        if ($CFG->restrictmodulesfor === 'all') {
            $courses = $DB->get_records_menu('course', array(), 'id', 'id, 1');
        } else {
            if ($CFG->restrictmodulesfor === 'requested') {
                $courses = $DB->get_records_menu('course', array('restrictmodules' => 1), 'id', 'id, 1');
            } else {
                $courses = array();
            }
        }
        if (!$dbman->table_exists('course_allowed_modules')) {
            // Upgrade must already have been run on this server. This might happen,
            // for example, during development of these changes.
            $courses = array();
        }
        $modidtoname = $DB->get_records_menu('modules', array(), 'id', 'id, name');
        $coursecount = count($courses);
        if ($coursecount) {
            $pbar = new progress_bar('allowedmods', 500, true);
            $transaction = $DB->start_delegated_transaction();
        }
        $i = 0;
        foreach ($courses as $courseid => $notused) {
            $i += 1;
            upgrade_set_timeout(60);
            // 1 minute per course should be fine.
            $allowedmoduleids = $DB->get_records_menu('course_allowed_modules', array('course' => $courseid), 'module', 'module, 1');
            if (empty($allowedmoduleids)) {
                // This seems to be the best match for backwards compatibility,
                // not necessarily with the old code in course_allowed_module function,
                // but with the code that used to be in the coures settings form.
                $allowedmoduleids = explode(',', $CFG->defaultallowedmodules);
                $allowedmoduleids = array_combine($allowedmoduleids, $allowedmoduleids);
            }
            $context = context_course::instance($courseid);
            list($roleids) = get_roles_with_cap_in_context($context, 'moodle/course:manageactivities');
            list($managerroleids) = get_roles_with_cap_in_context($context, 'moodle/site:config');
            foreach ($managerroleids as $roleid) {
                unset($roleids[$roleid]);
            }
            foreach ($modidtoname as $modid => $modname) {
                if (isset($allowedmoduleids[$modid])) {
                    // Module is allowed, no worries.
                    continue;
                }
                $capability = 'mod/' . $modname . ':addinstance';
                foreach ($roleids as $roleid) {
                    assign_capability($capability, CAP_PREVENT, $roleid, $context);
                }
            }
            $pbar->update($i, $coursecount, "Upgrading legacy course_allowed_modules data - {$i}/{$coursecount}.");
        }
        if ($coursecount) {
            $transaction->allow_commit();
        }
        upgrade_main_savepoint(true, 2012031500.01);
    }
    if ($oldversion < 2012031500.02) {
        // Define field restrictmodules to be dropped from course
        $table = new xmldb_table('course');
        $field = new xmldb_field('restrictmodules');
        // Conditionally launch drop field requested
        if ($dbman->field_exists($table, $field)) {
            $dbman->drop_field($table, $field);
        }
        // Since structure of 'course' table has changed we need to re-read $SITE from DB.
        $SITE = $DB->get_record('course', array('id' => $SITE->id));
        $COURSE = clone $SITE;
        upgrade_main_savepoint(true, 2012031500.02);
    }
    if ($oldversion < 2012031500.03) {
        // Define table course_allowed_modules to be dropped
        $table = new xmldb_table('course_allowed_modules');
        // Conditionally launch drop table for course_allowed_modules
        if ($dbman->table_exists($table)) {
            $dbman->drop_table($table);
        }
        upgrade_main_savepoint(true, 2012031500.03);
    }
    if ($oldversion < 2012031500.04) {
        // Clean up the old admin settings.
        unset_config('restrictmodulesfor');
        unset_config('restrictbydefault');
        unset_config('defaultallowedmodules');
        upgrade_main_savepoint(true, 2012031500.04);
    }
    if ($oldversion < 2012032300.02) {
        // Migrate the old admin debug setting.
        if ($CFG->debug == 38911) {
            set_config('debug', DEBUG_DEVELOPER);
        } else {
            if ($CFG->debug == 6143) {
                set_config('debug', DEBUG_ALL);
            }
        }
        upgrade_main_savepoint(true, 2012032300.02);
    }
    if ($oldversion < 2012042300.0) {
        // This change makes the course_section index unique.
        // Look for any duplicate course_sections entries. There should not be
        // any but on some busy systems we found a few, maybe due to previous
        // bugs.
        $transaction = $DB->start_delegated_transaction();
        $rs = $DB->get_recordset_sql('
                SELECT DISTINCT
                    cs.id, cs.course
                FROM
                    {course_sections} cs
                    INNER JOIN {course_sections} older
                        ON cs.course = older.course AND cs.section = older.section
                        AND older.id < cs.id');
        foreach ($rs as $rec) {
            $DB->delete_records('course_sections', array('id' => $rec->id));
            // We can't use rebuild_course_cache() here because introducing sectioncache later
            // so reset modinfo manually.
            $DB->set_field('course', 'modinfo', null, array('id' => $rec->course));
        }
        $rs->close();
        $transaction->allow_commit();
        // XMLDB does not allow changing index uniqueness - instead we must drop
        // index then add it again.
        // MDL-46182: The query to make the index unique uses the index,
        // so the removal of the non-unique version needs to happen after any
        // data changes have been made.
        $table = new xmldb_table('course_sections');
        $index = new xmldb_index('course_section', XMLDB_INDEX_NOTUNIQUE, array('course', 'section'));
        // Conditionally launch drop index course_section.
        if ($dbman->index_exists($table, $index)) {
            $dbman->drop_index($table, $index);
        }
        // Define index course_section (unique) to be added to course_sections
        $index = new xmldb_index('course_section', XMLDB_INDEX_UNIQUE, array('course', 'section'));
        // Conditionally launch add index course_section
        if (!$dbman->index_exists($table, $index)) {
            $dbman->add_index($table, $index);
        }
        // Main savepoint reached
        upgrade_main_savepoint(true, 2012042300.0);
    }
    if ($oldversion < 2012042300.02) {
        require_once $CFG->dirroot . '/completion/criteria/completion_criteria.php';
        // Delete orphaned criteria which were left when modules were removed
        if ($DB->get_dbfamily() === 'mysql') {
            $sql = "DELETE cc FROM {course_completion_criteria} cc\n                    LEFT JOIN {course_modules} cm ON cm.id = cc.moduleinstance\n                    WHERE cm.id IS NULL AND cc.criteriatype = " . COMPLETION_CRITERIA_TYPE_ACTIVITY;
        } else {
            $sql = "DELETE FROM {course_completion_criteria}\n                    WHERE NOT EXISTS (\n                        SELECT 'x' FROM {course_modules}\n                        WHERE {course_modules}.id = {course_completion_criteria}.moduleinstance)\n                    AND {course_completion_criteria}.criteriatype = " . COMPLETION_CRITERIA_TYPE_ACTIVITY;
        }
        $DB->execute($sql);
        // Main savepoint reached
        upgrade_main_savepoint(true, 2012042300.02);
    }
    if ($oldversion < 2012050300.01) {
        // Make sure deleted users do not have picture flag.
        $DB->set_field('user', 'picture', 0, array('deleted' => 1, 'picture' => 1));
        upgrade_main_savepoint(true, 2012050300.01);
    }
    if ($oldversion < 2012050300.02) {
        // Changing precision of field picture on table user to (10)
        $table = new xmldb_table('user');
        $field = new xmldb_field('picture', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0', 'secret');
        // Launch change of precision for field picture
        $dbman->change_field_precision($table, $field);
        // Main savepoint reached
        upgrade_main_savepoint(true, 2012050300.02);
    }
    if ($oldversion < 2012050300.03) {
        // Define field coursedisplay to be added to course
        $table = new xmldb_table('course');
        $field = new xmldb_field('coursedisplay', XMLDB_TYPE_INTEGER, '2', null, XMLDB_NOTNULL, null, '0', 'completionnotify');
        // Conditionally launch add field coursedisplay
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        // Since structure of 'course' table has changed we need to re-read $SITE from DB.
        $SITE = $DB->get_record('course', array('id' => $SITE->id));
        $COURSE = clone $SITE;
        // Main savepoint reached
        upgrade_main_savepoint(true, 2012050300.03);
    }
    if ($oldversion < 2012050300.04) {
        // Define table course_display to be dropped
        $table = new xmldb_table('course_display');
        // Conditionally launch drop table for course_display
        if ($dbman->table_exists($table)) {
            $dbman->drop_table($table);
        }
        // Main savepoint reached
        upgrade_main_savepoint(true, 2012050300.04);
    }
    if ($oldversion < 2012050300.05) {
        // Clean up removed admin setting.
        unset_config('navlinkcoursesections');
        upgrade_main_savepoint(true, 2012050300.05);
    }
    if ($oldversion < 2012050400.01) {
        // Define index sortorder (not unique) to be added to course
        $table = new xmldb_table('course');
        $index = new xmldb_index('sortorder', XMLDB_INDEX_NOTUNIQUE, array('sortorder'));
        // Conditionally launch add index sortorder
        if (!$dbman->index_exists($table, $index)) {
            $dbman->add_index($table, $index);
        }
        // Main savepoint reached
        upgrade_main_savepoint(true, 2012050400.01);
    }
    if ($oldversion < 2012050400.02) {
        // Clean up removed admin setting.
        unset_config('enablecourseajax');
        upgrade_main_savepoint(true, 2012050400.02);
    }
    if ($oldversion < 2012051100.01) {
        // Define field idnumber to be added to groups
        $table = new xmldb_table('groups');
        $field = new xmldb_field('idnumber', XMLDB_TYPE_CHAR, '100', null, XMLDB_NOTNULL, null, null, 'courseid');
        $index = new xmldb_index('idnumber', XMLDB_INDEX_NOTUNIQUE, array('idnumber'));
        // Conditionally launch add field idnumber
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        // Conditionally launch add index idnumber
        if (!$dbman->index_exists($table, $index)) {
            $dbman->add_index($table, $index);
        }
        // Define field idnumber to be added to groupings
        $table = new xmldb_table('groupings');
        $field = new xmldb_field('idnumber', XMLDB_TYPE_CHAR, '100', null, XMLDB_NOTNULL, null, null, 'name');
        $index = new xmldb_index('idnumber', XMLDB_INDEX_NOTUNIQUE, array('idnumber'));
        // Conditionally launch add field idnumber
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        // Conditionally launch add index idnumber
        if (!$dbman->index_exists($table, $index)) {
            $dbman->add_index($table, $index);
        }
        // Main savepoint reached
        upgrade_main_savepoint(true, 2012051100.01);
    }
    if ($oldversion < 2012051100.03) {
        // Amend course table to add sectioncache cache
        $table = new xmldb_table('course');
        $field = new xmldb_field('sectioncache', XMLDB_TYPE_TEXT, null, null, null, null, null, 'showgrades');
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        // Amend course_sections to add date, time and groupingid availability
        // conditions and a setting about whether to show them
        $table = new xmldb_table('course_sections');
        $field = new xmldb_field('availablefrom', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0', 'visible');
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        $field = new xmldb_field('availableuntil', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0', 'availablefrom');
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        $field = new xmldb_field('showavailability', XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, '0', 'availableuntil');
        // Conditionally launch add field showavailability
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        $field = new xmldb_field('groupingid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0', 'showavailability');
        // Conditionally launch add field groupingid
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        // Since structure of 'course' table has changed we need to re-read $SITE from DB.
        $SITE = $DB->get_record('course', array('id' => $SITE->id));
        $COURSE = clone $SITE;
        // Add course_sections_availability to add completion & grade availability conditions
        $table = new xmldb_table('course_sections_availability');
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
        $table->add_field('coursesectionid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null);
        $table->add_field('sourcecmid', XMLDB_TYPE_INTEGER, '10', null, null, null, null);
        $table->add_field('requiredcompletion', XMLDB_TYPE_INTEGER, '1', null, null, null, null);
        $table->add_field('gradeitemid', XMLDB_TYPE_INTEGER, '10', null, null, null, null);
        $table->add_field('grademin', XMLDB_TYPE_NUMBER, '10, 5', null, null, null, null);
        $table->add_field('grademax', XMLDB_TYPE_NUMBER, '10, 5', null, null, null, null);
        $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->add_key('coursesectionid', XMLDB_KEY_FOREIGN, array('coursesectionid'), 'course_sections', array('id'));
        $table->add_key('sourcecmid', XMLDB_KEY_FOREIGN, array('sourcecmid'), 'course_modules', array('id'));
        $table->add_key('gradeitemid', XMLDB_KEY_FOREIGN, array('gradeitemid'), 'grade_items', array('id'));
        if (!$dbman->table_exists($table)) {
            $dbman->create_table($table);
        }
        // Main savepoint reached
        upgrade_main_savepoint(true, 2012051100.03);
    }
    if ($oldversion < 2012052100.0) {
        // Define field referencefileid to be added to files.
        $table = new xmldb_table('files');
        // Define field referencefileid to be added to files.
        $field = new xmldb_field('referencefileid', XMLDB_TYPE_INTEGER, '10', null, null, null, null, 'sortorder');
        // Conditionally launch add field referencefileid.
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        // Define field referencelastsync to be added to files.
        $field = new xmldb_field('referencelastsync', XMLDB_TYPE_INTEGER, '10', null, null, null, null, 'referencefileid');
        // Conditionally launch add field referencelastsync.
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        // Define field referencelifetime to be added to files.
        $field = new xmldb_field('referencelifetime', XMLDB_TYPE_INTEGER, '10', null, null, null, null, 'referencelastsync');
        // Conditionally launch add field referencelifetime.
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        $key = new xmldb_key('referencefileid', XMLDB_KEY_FOREIGN, array('referencefileid'), 'files_reference', array('id'));
        // Launch add key referencefileid
        $dbman->add_key($table, $key);
        // Define table files_reference to be created.
        $table = new xmldb_table('files_reference');
        // Adding fields to table files_reference.
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
        $table->add_field('repositoryid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null);
        $table->add_field('lastsync', XMLDB_TYPE_INTEGER, '10', null, null, null, null);
        $table->add_field('lifetime', XMLDB_TYPE_INTEGER, '10', null, null, null, null);
        $table->add_field('reference', XMLDB_TYPE_TEXT, null, null, null, null, null);
        // Adding keys to table files_reference.
        $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->add_key('repositoryid', XMLDB_KEY_FOREIGN, array('repositoryid'), 'repository_instances', array('id'));
        // Conditionally launch create table for files_reference
        if (!$dbman->table_exists($table)) {
            $dbman->create_table($table);
        }
        // Main savepoint reached
        upgrade_main_savepoint(true, 2012052100.0);
    }
    if ($oldversion < 2012052500.03) {
        // fix invalid course_completion_records MDL-27368
        //first get all instances of duplicate records
        $sql = 'SELECT userid, course FROM {course_completions} WHERE (deleted IS NULL OR deleted <> 1) GROUP BY userid, course HAVING (count(id) > 1)';
        $duplicates = $DB->get_recordset_sql($sql, array());
        foreach ($duplicates as $duplicate) {
            $pointer = 0;
            //now get all the records for this user/course
            $sql = 'userid = ? AND course = ? AND (deleted IS NULL OR deleted <> 1)';
            $completions = $DB->get_records_select('course_completions', $sql, array($duplicate->userid, $duplicate->course), 'timecompleted DESC, timestarted DESC');
            $needsupdate = false;
            $origcompletion = null;
            foreach ($completions as $completion) {
                $pointer++;
                if ($pointer === 1) {
                    //keep 1st record but delete all others.
                    $origcompletion = $completion;
                } else {
                    //we need to keep the "oldest" of all these fields as the valid completion record.
                    $fieldstocheck = array('timecompleted', 'timestarted', 'timeenrolled');
                    foreach ($fieldstocheck as $f) {
                        if ($origcompletion->{$f} > $completion->{$f}) {
                            $origcompletion->{$f} = $completion->{$f};
                            $needsupdate = true;
                        }
                    }
                    $DB->delete_records('course_completions', array('id' => $completion->id));
                }
            }
            if ($needsupdate) {
                $DB->update_record('course_completions', $origcompletion);
            }
        }
        // Main savepoint reached
        upgrade_main_savepoint(true, 2012052500.03);
    }
    if ($oldversion < 2012052900.0) {
        // Clean up all duplicate records in the course_completions table in preparation
        // for adding a new index there.
        upgrade_course_completion_remove_duplicates('course_completions', array('userid', 'course'), array('timecompleted', 'timestarted', 'timeenrolled'));
        // Main savepoint reached
        upgrade_main_savepoint(true, 2012052900.0);
    }
    if ($oldversion < 2012052900.01) {
        // Add indexes to prevent new duplicates in the course_completions table.
        // Define index useridcourse (unique) to be added to course_completions
        $table = new xmldb_table('course_completions');
        $index = new xmldb_index('useridcourse', XMLDB_INDEX_UNIQUE, array('userid', 'course'));
        // Conditionally launch add index useridcourse
        if (!$dbman->index_exists($table, $index)) {
            $dbman->add_index($table, $index);
        }
        // Main savepoint reached
        upgrade_main_savepoint(true, 2012052900.01);
    }
    if ($oldversion < 2012052900.02) {
        // Clean up all duplicate records in the course_completion_crit_compl table in preparation
        // for adding a new index there.
        upgrade_course_completion_remove_duplicates('course_completion_crit_compl', array('userid', 'course', 'criteriaid'), array('timecompleted'));
        // Main savepoint reached
        upgrade_main_savepoint(true, 2012052900.02);
    }
    if ($oldversion < 2012052900.03) {
        // Add indexes to prevent new duplicates in the course_completion_crit_compl table.
        // Define index useridcoursecriteraid (unique) to be added to course_completion_crit_compl
        $table = new xmldb_table('course_completion_crit_compl');
        $index = new xmldb_index('useridcoursecriteraid', XMLDB_INDEX_UNIQUE, array('userid', 'course', 'criteriaid'));
        // Conditionally launch add index useridcoursecriteraid
        if (!$dbman->index_exists($table, $index)) {
            $dbman->add_index($table, $index);
        }
        // Main savepoint reached
        upgrade_main_savepoint(true, 2012052900.03);
    }
    if ($oldversion < 2012052900.04) {
        // Clean up all duplicate records in the course_completion_aggr_methd table in preparation
        // for adding a new index there.
        upgrade_course_completion_remove_duplicates('course_completion_aggr_methd', array('course', 'criteriatype'));
        // Main savepoint reached
        upgrade_main_savepoint(true, 2012052900.04);
    }
    if ($oldversion < 2012052900.05) {
        // Add indexes to prevent new duplicates in the course_completion_aggr_methd table.
        // Define index coursecriteratype (unique) to be added to course_completion_aggr_methd
        $table = new xmldb_table('course_completion_aggr_methd');
        $index = new xmldb_index('coursecriteriatype', XMLDB_INDEX_UNIQUE, array('course', 'criteriatype'));
        // Conditionally launch add index coursecriteratype
        if (!$dbman->index_exists($table, $index)) {
            $dbman->add_index($table, $index);
        }
        // Main savepoint reached
        upgrade_main_savepoint(true, 2012052900.05);
    }
    if ($oldversion < 2012060600.01) {
        // Add field referencehash to files_reference
        $table = new xmldb_table('files_reference');
        $field = new xmldb_field('referencehash', XMLDB_TYPE_CHAR, '40', null, XMLDB_NOTNULL, null, null, 'reference');
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        upgrade_main_savepoint(true, 2012060600.01);
    }
    if ($oldversion < 2012060600.02) {
        // Populate referencehash field with SHA1 hash of the reference - this shoudl affect only 2.3dev sites
        // that were using the feature for testing. Production sites have the table empty.
        $rs = $DB->get_recordset('files_reference', null, '', 'id, reference');
        foreach ($rs as $record) {
            $hash = sha1($record->reference);
            $DB->set_field('files_reference', 'referencehash', $hash, array('id' => $record->id));
        }
        $rs->close();
        upgrade_main_savepoint(true, 2012060600.02);
    }
    if ($oldversion < 2012060600.03) {
        // Merge duplicate records in files_reference that were created during the development
        // phase at 2.3dev sites. This is needed so we can create the unique index over
        // (repositoryid, referencehash) fields.
        $sql = "SELECT repositoryid, referencehash, MIN(id) AS minid\n                  FROM {files_reference}\n              GROUP BY repositoryid, referencehash\n                HAVING COUNT(*) > 1";
        $duprs = $DB->get_recordset_sql($sql);
        foreach ($duprs as $duprec) {
            // get the list of all ids in {files_reference} that need to be remapped
            $dupids = $DB->get_records_select('files_reference', "repositoryid = ? AND referencehash = ? AND id > ?", array($duprec->repositoryid, $duprec->referencehash, $duprec->minid), '', 'id');
            $dupids = array_keys($dupids);
            // relink records in {files} that are now referring to a duplicate record
            // in {files_reference} to refer to the first one
            list($subsql, $subparams) = $DB->get_in_or_equal($dupids);
            $DB->set_field_select('files', 'referencefileid', $duprec->minid, "referencefileid {$subsql}", $subparams);
            // and finally remove all orphaned records from {files_reference}
            $DB->delete_records_list('files_reference', 'id', $dupids);
        }
        $duprs->close();
        upgrade_main_savepoint(true, 2012060600.03);
    }
    if ($oldversion < 2012060600.04) {
        // Add a unique index over repositoryid and referencehash fields in files_reference table
        $table = new xmldb_table('files_reference');
        $index = new xmldb_index('uq_external_file', XMLDB_INDEX_UNIQUE, array('repositoryid', 'referencehash'));
        if (!$dbman->index_exists($table, $index)) {
            $dbman->add_index($table, $index);
        }
        upgrade_main_savepoint(true, 2012060600.04);
    }
    if ($oldversion < 2012061800.01) {
        // Define field screenreader to be dropped from user
        $table = new xmldb_table('user');
        $field = new xmldb_field('ajax');
        // Conditionally launch drop field screenreader
        if ($dbman->field_exists($table, $field)) {
            $dbman->drop_field($table, $field);
        }
        // Main savepoint reached
        upgrade_main_savepoint(true, 2012061800.01);
    }
    if ($oldversion < 2012062000.0) {
        // Add field newcontextid to backup_files_template
        $table = new xmldb_table('backup_files_template');
        $field = new xmldb_field('newcontextid', XMLDB_TYPE_INTEGER, '10', null, null, null, null, 'info');
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        upgrade_main_savepoint(true, 2012062000.0);
    }
    if ($oldversion < 2012062000.01) {
        // Add field newitemid to backup_files_template
        $table = new xmldb_table('backup_files_template');
        $field = new xmldb_field('newitemid', XMLDB_TYPE_INTEGER, '10', null, null, null, null, 'newcontextid');
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        upgrade_main_savepoint(true, 2012062000.01);
    }
    // Moodle v2.3.0 release upgrade line
    // Put any upgrade step following this
    if ($oldversion < 2012062500.02) {
        // Drop some old backup tables, not used anymore
        // Define table backup_files to be dropped
        $table = new xmldb_table('backup_files');
        // Conditionally launch drop table for backup_files
        if ($dbman->table_exists($table)) {
            $dbman->drop_table($table);
        }
        // Define table backup_ids to be dropped
        $table = new xmldb_table('backup_ids');
        // Conditionally launch drop table for backup_ids
        if ($dbman->table_exists($table)) {
            $dbman->drop_table($table);
        }
        // Main savepoint reached
        upgrade_main_savepoint(true, 2012062500.02);
    }
    if ($oldversion < 2012070600.04) {
        // Define table course_modules_avail_fields to be created
        $table = new xmldb_table('course_modules_avail_fields');
        // Adding fields to table course_modules_avail_fields
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
        $table->add_field('coursemoduleid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null);
        $table->add_field('userfield', XMLDB_TYPE_CHAR, '50', null, null, null, null);
        $table->add_field('customfieldid', XMLDB_TYPE_INTEGER, '10', null, null, null, null);
        $table->add_field('operator', XMLDB_TYPE_CHAR, '20', null, XMLDB_NOTNULL, null, null);
        $table->add_field('value', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null);
        // Adding keys to table course_modules_avail_fields
        $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->add_key('coursemoduleid', XMLDB_KEY_FOREIGN, array('coursemoduleid'), 'course_modules', array('id'));
        // Conditionally launch create table for course_modules_avail_fields
        if (!$dbman->table_exists($table)) {
            $dbman->create_table($table);
        }
        // Main savepoint reached
        upgrade_main_savepoint(true, 2012070600.04);
    }
    if ($oldversion < 2012070600.05) {
        // Define table course_sections_avail_fields to be created
        $table = new xmldb_table('course_sections_avail_fields');
        // Adding fields to table course_sections_avail_fields
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
        $table->add_field('coursesectionid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null);
        $table->add_field('userfield', XMLDB_TYPE_CHAR, '50', null, null, null, null);
        $table->add_field('customfieldid', XMLDB_TYPE_INTEGER, '10', null, null, null, null);
        $table->add_field('operator', XMLDB_TYPE_CHAR, '20', null, XMLDB_NOTNULL, null, null);
        $table->add_field('value', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null);
        // Adding keys to table course_sections_avail_fields
        $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->add_key('coursesectionid', XMLDB_KEY_FOREIGN, array('coursesectionid'), 'course_sections', array('id'));
        // Conditionally launch create table for course_sections_avail_fields
        if (!$dbman->table_exists($table)) {
            $dbman->create_table($table);
        }
        // Main savepoint reached
        upgrade_main_savepoint(true, 2012070600.05);
    }
    if ($oldversion < 2012070600.06) {
        // Drop "deleted" fields
        $table = new xmldb_table('course_completions');
        $field = new xmldb_field('timenotified');
        $field = new xmldb_field('deleted');
        // Conditionally launch drop field deleted from course_completions
        if ($dbman->field_exists($table, $field)) {
            $dbman->drop_field($table, $field);
        }
        $field = new xmldb_field('timenotified');
        // Conditionally launch drop field timenotified from course_completions
        if ($dbman->field_exists($table, $field)) {
            $dbman->drop_field($table, $field);
        }
        // Main savepoint reached
        upgrade_main_savepoint(true, 2012070600.06);
    }
    if ($oldversion < 2012070600.07) {
        $table = new xmldb_table('course_completion_crit_compl');
        $field = new xmldb_field('deleted');
        // Conditionally launch drop field deleted from course_completion_crit_compl
        if ($dbman->field_exists($table, $field)) {
            $dbman->drop_field($table, $field);
        }
        // Main savepoint reached
        upgrade_main_savepoint(true, 2012070600.07);
    }
    if ($oldversion < 2012070600.08) {
        // Drop unused table "course_completion_notify"
        $table = new xmldb_table('course_completion_notify');
        // Conditionally launch drop table course_completion_notify
        if ($dbman->table_exists($table)) {
            $dbman->drop_table($table);
        }
        // Main savepoint reached
        upgrade_main_savepoint(true, 2012070600.08);
    }
    if ($oldversion < 2012070600.09) {
        // Define index path (not unique) to be added to context
        $table = new xmldb_table('context');
        $index = new xmldb_index('path', XMLDB_INDEX_NOTUNIQUE, array('path'), array('varchar_pattern_ops'));
        // Recreate index with new pattern hint
        if ($DB->get_dbfamily() === 'postgres') {
            if ($dbman->index_exists($table, $index)) {
                $dbman->drop_index($table, $index);
            }
            $dbman->add_index($table, $index);
        }
        // Main savepoint reached
        upgrade_main_savepoint(true, 2012070600.09);
    }
    if ($oldversion < 2012070600.1) {
        // Define index name (unique) to be dropped form role
        $table = new xmldb_table('role');
        $index = new xmldb_index('name', XMLDB_INDEX_UNIQUE, array('name'));
        // Conditionally launch drop index name
        if ($dbman->index_exists($table, $index)) {
            $dbman->drop_index($table, $index);
        }
        // Main savepoint reached
        upgrade_main_savepoint(true, 2012070600.1);
    }
    if ($oldversion < 2012070600.11) {
        // Define index component-itemid-userid (not unique) to be added to role_assignments
        $table = new xmldb_table('role_assignments');
        $index = new xmldb_index('component-itemid-userid', XMLDB_INDEX_NOTUNIQUE, array('component', 'itemid', 'userid'));
        // Conditionally launch add index component-itemid-userid
        if (!$dbman->index_exists($table, $index)) {
            $dbman->add_index($table, $index);
        }
        // Main savepoint reached
        upgrade_main_savepoint(true, 2012070600.11);
    }
    if ($oldversion < 2012071900.01) {
        // Cleanup after simpeltests tool
        capabilities_cleanup('tool_unittest');
        unset_all_config_for_plugin('tool_unittest');
        upgrade_main_savepoint(true, 2012071900.01);
    }
    if ($oldversion < 2012072400.0) {
        // Remove obsolete xhtml strict setting - use THEME->doctype in theme config if necessary,
        // see theme_config->doctype in lib/outputlib.php for more details.
        unset_config('xmlstrictheaders');
        upgrade_main_savepoint(true, 2012072400.0);
    }
    if ($oldversion < 2012072401.0) {
        // Saves orphaned questions from the Dark Side
        upgrade_save_orphaned_questions();
        // Main savepoint reached
        upgrade_main_savepoint(true, 2012072401.0);
    }
    if ($oldversion < 2012072600.01) {
        // Handle events with empty eventtype //MDL-32827
        $DB->set_field('event', 'eventtype', 'site', array('eventtype' => '', 'courseid' => $SITE->id));
        $DB->set_field_select('event', 'eventtype', 'due', "eventtype = '' AND courseid != 0 AND groupid = 0 AND (modulename = 'assignment' OR modulename = 'assign')");
        $DB->set_field_select('event', 'eventtype', 'course', "eventtype = '' AND courseid != 0 AND groupid = 0");
        $DB->set_field_select('event', 'eventtype', 'group', "eventtype = '' AND groupid != 0");
        $DB->set_field_select('event', 'eventtype', 'user', "eventtype = '' AND userid != 0");
        // Main savepoint reached
        upgrade_main_savepoint(true, 2012072600.01);
    }
    if ($oldversion < 2012080200.02) {
        // Drop obsolete question upgrade field that should have been added to the install.xml.
        $table = new xmldb_table('question');
        $field = new xmldb_field('oldquestiontextformat', XMLDB_TYPE_INTEGER, '2', null, XMLDB_NOTNULL, null, '0');
        if ($dbman->field_exists($table, $field)) {
            $dbman->drop_field($table, $field);
        }
        upgrade_main_savepoint(true, 2012080200.02);
    }
    if ($oldversion < 2012081400.01) {
        // Move the ability to disable blogs to its own setting MDL-25012.
        if (isset($CFG->bloglevel)) {
            // Only change settings if existing setting was set.
            if (empty($CFG->bloglevel)) {
                set_config('enableblogs', 0);
                // Now set the bloglevel to a valid setting as the disabled setting has been removed.
                // This prevents confusing results when users enable the blog system in future.
                set_config('bloglevel', BLOG_USER_LEVEL);
            } else {
                set_config('enableblogs', 1);
            }
        }
        // Main savepoint reached
        upgrade_main_savepoint(true, 2012081400.01);
    }
    if ($oldversion < 2012081600.01) {
        // Delete removed setting - Google Maps API V2 will not work in 2013.
        unset_config('googlemapkey');
        upgrade_main_savepoint(true, 2012081600.01);
    }
    if ($oldversion < 2012082300.01) {
        // Add more custom enrol fields.
        $table = new xmldb_table('enrol');
        $field = new xmldb_field('customint5', XMLDB_TYPE_INTEGER, '10', null, null, null, null, 'customint4');
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        $field = new xmldb_field('customint6', XMLDB_TYPE_INTEGER, '10', null, null, null, null, 'customint5');
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        $field = new xmldb_field('customint7', XMLDB_TYPE_INTEGER, '10', null, null, null, null, 'customint6');
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        $field = new xmldb_field('customint8', XMLDB_TYPE_INTEGER, '10', null, null, null, null, 'customint7');
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        $field = new xmldb_field('customchar3', XMLDB_TYPE_CHAR, '1333', null, null, null, null, 'customchar2');
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        $field = new xmldb_field('customtext3', XMLDB_TYPE_TEXT, null, null, null, null, null, 'customtext2');
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        $field = new xmldb_field('customtext4', XMLDB_TYPE_TEXT, null, null, null, null, null, 'customtext3');
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2012082300.01);
    }
    if ($oldversion < 2012082300.02) {
        // Define field component to be added to groups_members
        $table = new xmldb_table('groups_members');
        $field = new xmldb_field('component', XMLDB_TYPE_CHAR, '100', null, XMLDB_NOTNULL, null, null, 'timeadded');
        // Conditionally launch add field component
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        // Define field itemid to be added to groups_members
        $field = new xmldb_field('itemid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0', 'component');
        // Conditionally launch add field itemid
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        // Main savepoint reached
        upgrade_main_savepoint(true, 2012082300.02);
    }
    if ($oldversion < 2012090500.0) {
        $subquery = 'SELECT b.id FROM {blog_external} b where b.id = ' . $DB->sql_cast_char2int('{post}.content', true);
        $sql = 'DELETE FROM {post}
                      WHERE {post}.module = \'blog_external\'
                            AND NOT EXISTS (' . $subquery . ')
                            AND ' . $DB->sql_isnotempty('post', 'uniquehash', false, false);
        $DB->execute($sql);
        upgrade_main_savepoint(true, 2012090500.0);
    }
    if ($oldversion < 2012090700.01) {
        // Add a category field in the course_request table
        $table = new xmldb_table('course_request');
        $field = new xmldb_field('category', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, 0, 'summaryformat');
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2012090700.01);
    }
    if ($oldversion < 2012091700.0) {
        // Dropping screenreader field from user.
        $table = new xmldb_table('user');
        $field = new xmldb_field('screenreader');
        if ($dbman->field_exists($table, $field)) {
            $dbman->drop_field($table, $field);
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2012091700.0);
    }
    if ($oldversion < 2012092100.01) {
        // Some folders still have a sortorder set, which is used for main files but is not
        // supported by the folder resource. We reset the value here.
        $sql = 'UPDATE {files} SET sortorder = ? WHERE component = ? AND filearea = ? AND sortorder <> ?';
        $DB->execute($sql, array(0, 'mod_folder', 'content', 0));
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2012092100.01);
    }
    if ($oldversion < 2012092600.0) {
        // Define index idname (unique) to be added to tag
        $table = new xmldb_table('tag');
        $index = new xmldb_index('idname', XMLDB_INDEX_UNIQUE, array('id', 'name'));
        // Conditionally launch add index idname
        if (!$dbman->index_exists($table, $index)) {
            $dbman->add_index($table, $index);
        }
        // Main savepoint reached
        upgrade_main_savepoint(true, 2012092600.0);
    }
    if ($oldversion < 2012101500.01) {
        // Find all orphaned blog associations that might exist.
        $sql = "SELECT ba.id\n                  FROM {blog_association} ba\n             LEFT JOIN {post} p\n                    ON p.id = ba.blogid\n                 WHERE p.id IS NULL";
        $orphanedrecordids = $DB->get_records_sql($sql);
        // Now delete these associations.
        foreach ($orphanedrecordids as $orphanedrecord) {
            $DB->delete_records('blog_association', array('id' => $orphanedrecord->id));
        }
        upgrade_main_savepoint(true, 2012101500.01);
    }
    if ($oldversion < 2012101800.02) {
        // Renaming backups using previous file naming convention.
        upgrade_rename_old_backup_files_using_shortname();
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2012101800.02);
    }
    if ($oldversion < 2012103001.0) {
        // create new event_subscriptions table
        $table = new xmldb_table('event_subscriptions');
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
        $table->add_field('url', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null);
        $table->add_field('courseid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
        $table->add_field('groupid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
        $table->add_field('userid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
        $table->add_field('pollinterval', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
        $table->add_field('lastupdated', XMLDB_TYPE_INTEGER, '10', null, null, null, null);
        $table->add_field('name', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null);
        $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
        if (!$dbman->table_exists($table)) {
            $dbman->create_table($table);
        }
        // Main savepoint reached
        upgrade_main_savepoint(true, 2012103001.0);
    }
    if ($oldversion < 2012103002.0) {
        // Add subscription field to the event table
        $table = new xmldb_table('event');
        $field = new xmldb_field('subscriptionid', XMLDB_TYPE_INTEGER, '10', null, null, null, null, 'timemodified');
        // Conditionally launch add field subscriptionid
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        upgrade_main_savepoint(true, 2012103002.0);
    }
    if ($oldversion < 2012103003.0) {
        // Fix uuid field in event table to match RFC-2445 UID property.
        $table = new xmldb_table('event');
        $field = new xmldb_field('uuid', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, 'visible');
        // The column already exists, so make sure there are no nulls (crazy mysql).
        $DB->set_field_select('event', 'uuid', '', "uuid IS NULL");
        // Changing precision of field uuid on table event to (255).
        $dbman->change_field_precision($table, $field);
        // Main savepoint reached
        upgrade_main_savepoint(true, 2012103003.0);
    }
    if ($oldversion < 2012110200.0) {
        // Define table course_format_options to be created
        $table = new xmldb_table('course_format_options');
        // Adding fields to table course_format_options
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
        $table->add_field('courseid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null);
        $table->add_field('format', XMLDB_TYPE_CHAR, '21', null, XMLDB_NOTNULL, null, null);
        $table->add_field('sectionid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0', 'format');
        $table->add_field('name', XMLDB_TYPE_CHAR, '100', null, XMLDB_NOTNULL, null, null);
        $table->add_field('value', XMLDB_TYPE_TEXT, null, null, null, null, null);
        // Adding keys to table course_format_options
        $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->add_key('courseid', XMLDB_KEY_FOREIGN, array('courseid'), 'course', array('id'));
        // Adding indexes to table course_format_options
        $table->add_index('formatoption', XMLDB_INDEX_UNIQUE, array('courseid', 'format', 'sectionid', 'name'));
        // Conditionally launch create table for course_format_options
        if (!$dbman->table_exists($table)) {
            $dbman->create_table($table);
        }
        // Changing type of field format on table course to char with length 21
        $table = new xmldb_table('course');
        $field = new xmldb_field('format', XMLDB_TYPE_CHAR, '21', null, XMLDB_NOTNULL, null, 'topics', 'summaryformat');
        // Launch change of type for field format
        $dbman->change_field_type($table, $field);
        // Since structure of 'course' table has changed we need to re-read $SITE from DB.
        $SITE = $DB->get_record('course', array('id' => $SITE->id));
        $COURSE = clone $SITE;
        // Main savepoint reached
        upgrade_main_savepoint(true, 2012110200.0);
    }
    if ($oldversion < 2012110201.0) {
        // Copy fields 'coursedisplay', 'numsections', 'hiddensections' from table {course}
        // to table {course_format_options} as the additional format options
        $fields = array();
        $table = new xmldb_table('course');
        foreach (array('coursedisplay', 'numsections', 'hiddensections') as $fieldname) {
            // first check that fields still exist
            $field = new xmldb_field($fieldname);
            if ($dbman->field_exists($table, $field)) {
                $fields[] = $fieldname;
            }
        }
        if (!empty($fields)) {
            $transaction = $DB->start_delegated_transaction();
            $rs = $DB->get_recordset_sql('SELECT id, format, ' . join(',', $fields) . '
                FROM {course}
                WHERE format <> ? AND format <> ?', array('scorm', 'social'));
            // (do not copy fields from scrom and social formats, we already know that they are not used)
            foreach ($rs as $rec) {
                foreach ($fields as $field) {
                    try {
                        $DB->insert_record('course_format_options', array('courseid' => $rec->id, 'format' => $rec->format, 'sectionid' => 0, 'name' => $field, 'value' => $rec->{$field}));
                    } catch (dml_exception $e) {
                        // index 'courseid,format,sectionid,name' violation
                        // continue; the entry in course_format_options already exists, use it
                    }
                }
            }
            $rs->close();
            $transaction->allow_commit();
            // Drop fields from table course
            foreach ($fields as $fieldname) {
                $field = new xmldb_field($fieldname);
                $dbman->drop_field($table, $field);
            }
        }
        // Since structure of 'course' table has changed we need to re-read $SITE from DB.
        $SITE = $DB->get_record('course', array('id' => $SITE->id));
        $COURSE = clone $SITE;
        // Main savepoint reached
        upgrade_main_savepoint(true, 2012110201.0);
    }
    if ($oldversion < 2012110700.01) {
        // Define field caller_component to be added to portfolio_log.
        $table = new xmldb_table('portfolio_log');
        $field = new xmldb_field('caller_component', XMLDB_TYPE_CHAR, '255', null, null, null, null, 'caller_file');
        // Conditionally launch add field caller_component.
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2012110700.01);
    }
    if ($oldversion < 2012111200.0) {
        // Define table temp_enroled_template to be created
        $table = new xmldb_table('temp_enroled_template');
        // Adding fields to table temp_enroled_template
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
        $table->add_field('userid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
        $table->add_field('courseid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
        $table->add_field('roleid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null);
        // Adding keys to table temp_enroled_template
        $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
        // Adding indexes to table temp_enroled_template
        $table->add_index('userid', XMLDB_INDEX_NOTUNIQUE, array('userid'));
        $table->add_index('courseid', XMLDB_INDEX_NOTUNIQUE, array('courseid'));
        $table->add_index('roleid', XMLDB_INDEX_NOTUNIQUE, array('roleid'));
        // Conditionally launch create table for temp_enroled_template
        if (!$dbman->table_exists($table)) {
            $dbman->create_table($table);
        }
        // Define table temp_log_template to be created
        $table = new xmldb_table('temp_log_template');
        // Adding fields to table temp_log_template
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
        $table->add_field('userid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
        $table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
        $table->add_field('action', XMLDB_TYPE_CHAR, '40', null, XMLDB_NOTNULL, null, null);
        // Adding keys to table temp_log_template
        $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
        // Adding indexes to table temp_log_template
        $table->add_index('action', XMLDB_INDEX_NOTUNIQUE, array('action'));
        $table->add_index('course', XMLDB_INDEX_NOTUNIQUE, array('course'));
        $table->add_index('user', XMLDB_INDEX_NOTUNIQUE, array('userid'));
        $table->add_index('usercourseaction', XMLDB_INDEX_NOTUNIQUE, array('userid', 'course', 'action'));
        // Conditionally launch create table for temp_log_template
        if (!$dbman->table_exists($table)) {
            $dbman->create_table($table);
        }
        // Main savepoint reached
        upgrade_main_savepoint(true, 2012111200.0);
    }
    if ($oldversion < 2012111200.01) {
        // Force the rebuild of the cache of every courses, some cached information could contain wrong icon references.
        $DB->execute('UPDATE {course} set modinfo = ?, sectioncache = ?', array(null, null));
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2012111200.01);
    }
    if ($oldversion < 2012111601.01) {
        // Clea up after old shared memory caching support.
        unset_config('cachetype');
        unset_config('rcache');
        unset_config('rcachettl');
        unset_config('intcachemax');
        unset_config('memcachedhosts');
        unset_config('memcachedpconn');
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2012111601.01);
    }
    if ($oldversion < 2012112100.0) {
        // Define field eventtype to be added to event_subscriptions.
        $table = new xmldb_table('event_subscriptions');
        $field = new xmldb_field('eventtype', XMLDB_TYPE_CHAR, '20', null, XMLDB_NOTNULL, null, null, 'userid');
        // Conditionally launch add field eventtype.
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2012112100.0);
    }
    // Moodle v2.4.0 release upgrade line
    // Put any upgrade step following this
    if ($oldversion < 2012120300.01) {
        // Make sure site-course has format='site' //MDL-36840
        if ($SITE->format !== 'site') {
            $DB->set_field('course', 'format', 'site', array('id' => $SITE->id));
            $SITE->format = 'site';
            $COURSE->format = 'site';
        }
        // Main savepoint reached
        upgrade_main_savepoint(true, 2012120300.01);
    }
    if ($oldversion < 2012120300.04) {
        // Remove "_utf8" suffix from all langs in course table.
        $langs = $DB->get_records_sql("SELECT DISTINCT lang FROM {course} WHERE lang LIKE ?", array('%_utf8'));
        foreach ($langs as $lang => $unused) {
            $newlang = str_replace('_utf8', '', $lang);
            $sql = "UPDATE {course} SET lang = :newlang WHERE lang = :lang";
            $DB->execute($sql, array('newlang' => $newlang, 'lang' => $lang));
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2012120300.04);
    }
    if ($oldversion < 2012123000.0) {
        // Purge removed module filters and all their settings.
        $tables = array('filter_active', 'filter_config');
        foreach ($tables as $table) {
            $DB->delete_records_select($table, "filter LIKE 'mod/%'");
            $filters = $DB->get_records_sql("SELECT DISTINCT filter FROM {{$table}} WHERE filter LIKE 'filter/%'");
            foreach ($filters as $filter) {
                $DB->set_field($table, 'filter', substr($filter->filter, 7), array('filter' => $filter->filter));
            }
        }
        $configs = array('stringfilters', 'filterall');
        foreach ($configs as $config) {
            if ($filters = get_config(null, $config)) {
                $filters = explode(',', $filters);
                $newfilters = array();
                foreach ($filters as $filter) {
                    if (strpos($filter, '/') === false) {
                        $newfilters[] = $filter;
                    } else {
                        if (strpos($filter, 'filter/') === 0) {
                            $newfilters[] = substr($filter, 7);
                        }
                    }
                }
                $filters = implode(',', $newfilters);
                set_config($config, $filters);
            }
        }
        unset($tables);
        unset($table);
        unset($configs);
        unset($newfilters);
        unset($filters);
        unset($filter);
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2012123000.0);
    }
    if ($oldversion < 2013021100.01) {
        // Make sure there are no bogus nulls in old MySQL tables.
        $DB->set_field_select('user', 'password', '', "password IS NULL");
        // Changing precision of field password on table user to (255).
        $table = new xmldb_table('user');
        $field = new xmldb_field('password', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, 'username');
        // Launch change of precision for field password.
        $dbman->change_field_precision($table, $field);
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2013021100.01);
    }
    if ($oldversion < 2013021800.0) {
        // Add the site identifier to the cache config's file.
        $siteidentifier = $DB->get_field('config', 'value', array('name' => 'siteidentifier'));
        cache_helper::update_site_identifier($siteidentifier);
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2013021800.0);
    }
    if ($oldversion < 2013021801.0) {
        // Fixing possible wrong MIME types for SMART Notebook files.
        $extensions = array('%.gallery', '%.galleryitem', '%.gallerycollection', '%.nbk', '%.notebook', '%.xbk');
        $select = $DB->sql_like('filename', '?', false);
        foreach ($extensions as $extension) {
            $DB->set_field_select('files', 'mimetype', 'application/x-smarttech-notebook', $select, array($extension));
        }
        upgrade_main_savepoint(true, 2013021801.0);
    }
    if ($oldversion < 2013021801.01) {
        // This upgrade step is re-written under MDL-38228 (see below).
        /*
        // Retrieve the list of course_sections as a recordset to save memory
        $coursesections = $DB->get_recordset('course_sections', null, 'course, id', 'id, course, sequence');
        foreach ($coursesections as $coursesection) {
            // Retrieve all of the actual modules in this course and section combination to reduce DB calls
            $actualsectionmodules = $DB->get_records('course_modules',
                    array('course' => $coursesection->course, 'section' => $coursesection->id), '', 'id, section');
        
            // Break out the current sequence so that we can compare it
            $currentsequence = explode(',', $coursesection->sequence);
            $newsequence = array();
        
            // Check each of the modules in the current sequence
            foreach ($currentsequence as $module) {
                if (isset($actualsectionmodules[$module])) {
                    $newsequence[] = $module;
                    // We unset the actualsectionmodules so that we don't get duplicates and that we can add orphaned
                    // modules later
                    unset($actualsectionmodules[$module]);
                }
            }
        
            // Append any modules which have somehow been orphaned
            foreach ($actualsectionmodules as $module) {
                $newsequence[] = $module->id;
            }
        
            // Piece it all back together
            $sequence = implode(',', $newsequence);
        
            // Only update if there have been changes
            if ($sequence !== $coursesection->sequence) {
                $coursesection->sequence = $sequence;
                $DB->update_record('course_sections', $coursesection);
        
                // And clear the sectioncache and modinfo cache - they'll be regenerated on next use
                $course = new stdClass();
                $course->id = $coursesection->course;
                $course->sectioncache = null;
                $course->modinfo = null;
                $DB->update_record('course', $course);
            }
        }
        $coursesections->close();
        */
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2013021801.01);
    }
    if ($oldversion < 2013021902.0) {
        // ISO country change: Netherlands Antilles is split into BQ, CW & SX
        // http://www.iso.org/iso/iso_3166-1_newsletter_vi-8_split_of_the_dutch_antilles_final-en.pdf
        $sql = "UPDATE {user} SET country = '' WHERE country = ?";
        $DB->execute($sql, array('AN'));
        upgrade_main_savepoint(true, 2013021902.0);
    }
    if ($oldversion < 2013022600.0) {
        // Delete entries regarding invalid 'interests' option which breaks course.
        $DB->delete_records('course_sections_avail_fields', array('userfield' => 'interests'));
        $DB->delete_records('course_modules_avail_fields', array('userfield' => 'interests'));
        // Clear course cache (will be rebuilt on first visit) in case of changes to these.
        $DB->execute('UPDATE {course} set modinfo = ?, sectioncache = ?', array(null, null));
        upgrade_main_savepoint(true, 2013022600.0);
    }
    // Add index to field "timemodified" for grade_grades_history table.
    if ($oldversion < 2013030400.0) {
        $table = new xmldb_table('grade_grades_history');
        $field = new xmldb_field('timemodified');
        if ($dbman->field_exists($table, $field)) {
            $index = new xmldb_index('timemodified', XMLDB_INDEX_NOTUNIQUE, array('timemodified'));
            if (!$dbman->index_exists($table, $index)) {
                $dbman->add_index($table, $index);
            }
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2013030400.0);
    }
    if ($oldversion < 2013030400.02) {
        // Cleanup qformat blackboard settings.
        unset_all_config_for_plugin('qformat_blackboard');
        upgrade_main_savepoint(true, 2013030400.02);
    }
    // This is checking to see if the site has been running a specific version with a bug in it
    // because this upgrade step is slow and is only needed if the site has been running with the affected versions.
    if ($oldversion >= 2012062504.08 && $oldversion < 2012062504.13) {
        // This upgrade step is re-written under MDL-38228 (see below).
        /*
                // Retrieve the list of course_sections as a recordset to save memory.
                // This is to fix a regression caused by MDL-37939.
                // In this case the upgrade step is fixing records where:
                // The data in course_sections.sequence contains the correct module id
                // The section field for on the course modules table may have been updated to point to the incorrect id.
        
                // This query is looking for sections where the sequence is not in sync with the course_modules table.
                // The syntax for the like query is looking for a value in a comma separated list.
                // It adds a comma to either site of the list and then searches for LIKE '%,id,%'.
                $sequenceconcat = $DB->sql_concat("','", 's.sequence', "','");
                $moduleconcat = $DB->sql_concat("'%,'", 'cm.id', "',%'");
                $sql = 'SELECT s2.id, s2.course, s2.sequence
               FROM {course_sections} s2
               JOIN(
                   SELECT DISTINCT s.id
                   FROM
                   {course_modules} cm
                   JOIN {course_sections} s
                   ON
                       cm.course = s.course
                   WHERE cm.section != s.id AND ' . $sequenceconcat . ' LIKE ' . $moduleconcat . '
               ) d
               ON s2.id = d.id';
                $coursesections = $DB->get_recordset_sql($sql);
        
                foreach ($coursesections as $coursesection) {
           // Retrieve all of the actual modules in this course and section combination to reduce DB calls.
           $actualsectionmodules = $DB->get_records('course_modules',
                   array('course' => $coursesection->course, 'section' => $coursesection->id), '', 'id, section');
        
           // Break out the current sequence so that we can compare it.
           $currentsequence = explode(',', $coursesection->sequence);
           $orphanlist = array();
        
           // Check each of the modules in the current sequence.
           foreach ($currentsequence as $cmid) {
               if (!empty($cmid) && !isset($actualsectionmodules[$cmid])) {
                   $orphanlist[] = $cmid;
               }
           }
        
           if (!empty($orphanlist)) {
               list($sql, $params) = $DB->get_in_or_equal($orphanlist, SQL_PARAMS_NAMED);
               $sql = "id $sql";
        
               $DB->set_field_select('course_modules', 'section', $coursesection->id, $sql, $params);
        
               // And clear the sectioncache and modinfo cache - they'll be regenerated on next use.
               $course = new stdClass();
               $course->id = $coursesection->course;
               $course->sectioncache = null;
               $course->modinfo = null;
               $DB->update_record('course', $course);
           }
                }
                $coursesections->close();
        
                // No savepoint needed for this change.
        */
    }
    if ($oldversion < 2013032200.01) {
        // GD is now always available
        set_config('gdversion', 2);
        upgrade_main_savepoint(true, 2013032200.01);
    }
    if ($oldversion < 2013032600.03) {
        // Fixing possible wrong MIME type for MIME HTML (MHTML) files.
        $extensions = array('%.mht', '%.mhtml');
        $select = $DB->sql_like('filename', '?', false);
        foreach ($extensions as $extension) {
            $DB->set_field_select('files', 'mimetype', 'message/rfc822', $select, array($extension));
        }
        upgrade_main_savepoint(true, 2013032600.03);
    }
    if ($oldversion < 2013032600.04) {
        // MDL-31983 broke the quiz version number. Fix it.
        $DB->set_field('modules', 'version', '2013021500', array('name' => 'quiz', 'version' => '2013310100'));
        upgrade_main_savepoint(true, 2013032600.04);
    }
    if ($oldversion < 2013040200.0) {
        // Add openbadges tables.
        // Define table 'badge' to be created.
        $table = new xmldb_table('badge');
        // Adding fields to table 'badge'.
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null);
        $table->add_field('name', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, 'id');
        $table->add_field('description', XMLDB_TYPE_TEXT, null, null, null, null, null, 'name');
        $table->add_field('image', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, 'description');
        $table->add_field('timecreated', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0', 'image');
        $table->add_field('timemodified', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0', 'timecreated');
        $table->add_field('usercreated', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, 'timemodified');
        $table->add_field('usermodified', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, 'usercreated');
        $table->add_field('issuername', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, 'usermodified');
        $table->add_field('issuerurl', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, 'issuername');
        $table->add_field('issuercontact', XMLDB_TYPE_CHAR, '255', null, null, null, null, 'issuerurl');
        $table->add_field('expiredate', XMLDB_TYPE_INTEGER, '10', null, null, null, null, 'issuercontact');
        $table->add_field('expireperiod', XMLDB_TYPE_INTEGER, '10', null, null, null, null, 'expiredate');
        $table->add_field('type', XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, '1', 'expireperiod');
        $table->add_field('courseid', XMLDB_TYPE_INTEGER, '10', null, null, null, null, 'type');
        $table->add_field('message', XMLDB_TYPE_TEXT, null, null, XMLDB_NOTNULL, null, null, 'courseid');
        $table->add_field('messagesubject', XMLDB_TYPE_TEXT, null, null, XMLDB_NOTNULL, null, null, 'message');
        $table->add_field('attachment', XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, '1', 'messagesubject');
        $table->add_field('notification', XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, '1', 'attachment');
        $table->add_field('status', XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, '0', 'notification');
        $table->add_field('nextcron', XMLDB_TYPE_INTEGER, '10', null, null, null, null, 'status');
        // Adding keys to table 'badge'.
        $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->add_key('fk_courseid', XMLDB_KEY_FOREIGN, array('courseid'), 'course', array('id'));
        $table->add_key('fk_usermodified', XMLDB_KEY_FOREIGN, array('usermodified'), 'user', array('id'));
        $table->add_key('fk_usercreated', XMLDB_KEY_FOREIGN, array('usercreated'), 'user', array('id'));
        // Adding indexes to table 'badge'.
        $table->add_index('type', XMLDB_INDEX_NOTUNIQUE, array('type'));
        // Conditionally launch create table for 'badge'.
        if (!$dbman->table_exists($table)) {
            $dbman->create_table($table);
        }
        // Define table 'badge_criteria' to be created.
        $table = new xmldb_table('badge_criteria');
        // Adding fields to table 'badge_criteria'.
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null);
        $table->add_field('badgeid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0', 'id');
        $table->add_field('criteriatype', XMLDB_TYPE_INTEGER, '10', null, null, null, null, 'badgeid');
        $table->add_field('method', XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, '1', 'criteriatype');
        // Adding keys to table 'badge_criteria'.
        $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->add_key('fk_badgeid', XMLDB_KEY_FOREIGN, array('badgeid'), 'badge', array('id'));
        // Adding indexes to table 'badge_criteria'.
        $table->add_index('criteriatype', XMLDB_INDEX_NOTUNIQUE, array('criteriatype'));
        $table->add_index('badgecriteriatype', XMLDB_INDEX_UNIQUE, array('badgeid', 'criteriatype'));
        // Conditionally launch create table for 'badge_criteria'.
        if (!$dbman->table_exists($table)) {
            $dbman->create_table($table);
        }
        // Define table 'badge_criteria_param' to be created.
        $table = new xmldb_table('badge_criteria_param');
        // Adding fields to table 'badge_criteria_param'.
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null);
        $table->add_field('critid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, 'id');
        $table->add_field('name', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, 'critid');
        $table->add_field('value', XMLDB_TYPE_CHAR, '255', null, null, null, null, 'name');
        // Adding keys to table 'badge_criteria_param'.
        $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->add_key('fk_critid', XMLDB_KEY_FOREIGN, array('critid'), 'badge_criteria', array('id'));
        // Conditionally launch create table for 'badge_criteria_param'.
        if (!$dbman->table_exists($table)) {
            $dbman->create_table($table);
        }
        // Define table 'badge_issued' to be created.
        $table = new xmldb_table('badge_issued');
        // Adding fields to table 'badge_issued'.
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null);
        $table->add_field('badgeid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0', 'id');
        $table->add_field('userid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0', 'badgeid');
        $table->add_field('uniquehash', XMLDB_TYPE_TEXT, null, null, XMLDB_NOTNULL, null, null, 'userid');
        $table->add_field('dateissued', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0', 'uniquehash');
        $table->add_field('dateexpire', XMLDB_TYPE_INTEGER, '10', null, null, null, null, 'dateissued');
        $table->add_field('visible', XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, '0', 'dateexpire');
        $table->add_field('issuernotified', XMLDB_TYPE_INTEGER, '10', null, null, null, null, 'visible');
        // Adding keys to table 'badge_issued'.
        $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->add_key('fk_badgeid', XMLDB_KEY_FOREIGN, array('badgeid'), 'badge', array('id'));
        $table->add_key('fk_userid', XMLDB_KEY_FOREIGN, array('userid'), 'user', array('id'));
        $table->add_index('badgeuser', XMLDB_INDEX_UNIQUE, array('badgeid', 'userid'));
        // Conditionally launch create table for 'badge_issued'.
        if (!$dbman->table_exists($table)) {
            $dbman->create_table($table);
        }
        // Define table 'badge_criteria_met' to be created.
        $table = new xmldb_table('badge_criteria_met');
        // Adding fields to table 'badge_criteria_met'.
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null);
        $table->add_field('issuedid', XMLDB_TYPE_INTEGER, '10', null, null, null, null, 'id');
        $table->add_field('critid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, 'issuedid');
        $table->add_field('userid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, 'critid');
        $table->add_field('datemet', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, 'userid');
        // Adding keys to table 'badge_criteria_met'
        $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->add_key('fk_critid', XMLDB_KEY_FOREIGN, array('critid'), 'badge_criteria', array('id'));
        $table->add_key('fk_userid', XMLDB_KEY_FOREIGN, array('userid'), 'user', array('id'));
        $table->add_key('fk_issuedid', XMLDB_KEY_FOREIGN, array('issuedid'), 'badge_issued', array('id'));
        // Conditionally launch create table for 'badge_criteria_met'.
        if (!$dbman->table_exists($table)) {
            $dbman->create_table($table);
        }
        // Define table 'badge_manual_award' to be created.
        $table = new xmldb_table('badge_manual_award');
        // Adding fields to table 'badge_manual_award'.
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null);
        $table->add_field('badgeid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, 'id');
        $table->add_field('recipientid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, 'badgeid');
        $table->add_field('issuerid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, 'recipientid');
        $table->add_field('issuerrole', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, 'issuerid');
        $table->add_field('datemet', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, 'issuerrole');
        // Adding keys to table 'badge_manual_award'.
        $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->add_key('fk_badgeid', XMLDB_KEY_FOREIGN, array('badgeid'), 'badge', array('id'));
        $table->add_key('fk_recipientid', XMLDB_KEY_FOREIGN, array('recipientid'), 'user', array('id'));
        $table->add_key('fk_issuerid', XMLDB_KEY_FOREIGN, array('issuerid'), 'user', array('id'));
        $table->add_key('fk_issuerrole', XMLDB_KEY_FOREIGN, array('issuerrole'), 'role', array('id'));
        // Conditionally launch create table for 'badge_manual_award'.
        if (!$dbman->table_exists($table)) {
            $dbman->create_table($table);
        }
        // Define table 'badge_backpack' to be created.
        $table = new xmldb_table('badge_backpack');
        // Adding fields to table 'badge_backpack'.
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null);
        $table->add_field('userid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0', 'id');
        $table->add_field('email', XMLDB_TYPE_CHAR, '100', null, XMLDB_NOTNULL, null, null, 'userid');
        $table->add_field('backpackurl', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, 'email');
        $table->add_field('backpackuid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, 'backpackurl');
        $table->add_field('backpackgid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, 'backpackuid');
        $table->add_field('autosync', XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, '0', 'backpackgid');
        $table->add_field('password', XMLDB_TYPE_CHAR, '50', null, null, null, null, 'autosync');
        // Adding keys to table 'badge_backpack'.
        $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->add_key('fk_userid', XMLDB_KEY_FOREIGN, array('userid'), 'user', array('id'));
        // Conditionally launch create table for 'badge_backpack'.
        if (!$dbman->table_exists($table)) {
            $dbman->create_table($table);
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2013040200.0);
    }
    if ($oldversion < 2013040201.0) {
        // Convert name field in event table to text type as RFC-2445 doesn't have any limitation on it.
        $table = new xmldb_table('event');
        $field = new xmldb_field('name', XMLDB_TYPE_TEXT, null, null, XMLDB_NOTNULL, null, null);
        if ($dbman->field_exists($table, $field)) {
            $dbman->change_field_type($table, $field);
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2013040201.0);
    }
    if ($oldversion < 2013040300.01) {
        // Define field completionstartonenrol to be dropped from course.
        $table = new xmldb_table('course');
        $field = new xmldb_field('completionstartonenrol');
        // Conditionally launch drop field completionstartonenrol.
        if ($dbman->field_exists($table, $field)) {
            $dbman->drop_field($table, $field);
        }
        // Since structure of 'course' table has changed we need to re-read $SITE from DB.
        $SITE = $DB->get_record('course', array('id' => $SITE->id));
        $COURSE = clone $SITE;
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2013040300.01);
    }
    if ($oldversion < 2013041200.0) {
        // MDL-29877 Some bad restores created grade items with no category information.
        $sql = "UPDATE {grade_items}\n                   SET categoryid = courseid\n                 WHERE itemtype <> 'course' and itemtype <> 'category'\n                       AND categoryid IS NULL";
        $DB->execute($sql);
        upgrade_main_savepoint(true, 2013041200.0);
    }
    if ($oldversion < 2013041600.0) {
        // Copy constants from /course/lib.php instead of including the whole library:
        $c = array('FRONTPAGENEWS' => 0, 'FRONTPAGECOURSELIST' => 1, 'FRONTPAGECATEGORYNAMES' => 2, 'FRONTPAGETOPICONLY' => 3, 'FRONTPAGECATEGORYCOMBO' => 4, 'FRONTPAGEENROLLEDCOURSELIST' => 5, 'FRONTPAGEALLCOURSELIST' => 6, 'FRONTPAGECOURSESEARCH' => 7);
        // Update frontpage settings $CFG->frontpage and $CFG->frontpageloggedin. In 2.4 there was too much of hidden logic about them.
        // This script tries to make sure that with the new (more user-friendly) frontpage settings the frontpage looks as similar as possible to what it was before upgrade.
        $ncourses = $DB->count_records('course');
        foreach (array('frontpage', 'frontpageloggedin') as $configkey) {
            if ($frontpage = explode(',', $CFG->{$configkey})) {
                $newfrontpage = array();
                foreach ($frontpage as $v) {
                    switch ($v) {
                        case $c['FRONTPAGENEWS']:
                            // Not related to course listings, leave as it is.
                            $newfrontpage[] = $c['FRONTPAGENEWS'];
                            break;
                        case $c['FRONTPAGECOURSELIST']:
                            if ($configkey === 'frontpageloggedin' && empty($CFG->disablemycourses)) {
                                // In 2.4 unless prohibited in config, the "list of courses" was considered "list of enrolled courses" plus course search box.
                                $newfrontpage[] = $c['FRONTPAGEENROLLEDCOURSELIST'];
                            } else {
                                if ($ncourses <= 200) {
                                    // Still list of courses was only displayed in there were less than 200 courses in system. Otherwise - search box only.
                                    $newfrontpage[] = $c['FRONTPAGEALLCOURSELIST'];
                                    break;
                                    // skip adding search box
                                }
                            }
                            if (!in_array($c['FRONTPAGECOURSESEARCH'], $newfrontpage)) {
                                $newfrontpage[] = $c['FRONTPAGECOURSESEARCH'];
                            }
                            break;
                        case $c['FRONTPAGECATEGORYNAMES']:
                            // In 2.4 search box was displayed automatically after categories list. In 2.5 it is displayed as a separate setting.
                            $newfrontpage[] = $c['FRONTPAGECATEGORYNAMES'];
                            if (!in_array($c['FRONTPAGECOURSESEARCH'], $newfrontpage)) {
                                $newfrontpage[] = $c['FRONTPAGECOURSESEARCH'];
                            }
                            break;
                        case $c['FRONTPAGECATEGORYCOMBO']:
                            $maxcourses = empty($CFG->numcoursesincombo) ? 500 : $CFG->numcoursesincombo;
                            // In 2.4 combo list was not displayed if there are more than $CFG->numcoursesincombo courses in the system.
                            if ($ncourses < $maxcourses) {
                                $newfrontpage[] = $c['FRONTPAGECATEGORYCOMBO'];
                            }
                            if (!in_array($c['FRONTPAGECOURSESEARCH'], $newfrontpage)) {
                                $newfrontpage[] = $c['FRONTPAGECOURSESEARCH'];
                            }
                            break;
                    }
                }
                set_config($configkey, join(',', $newfrontpage));
            }
        }
        // $CFG->numcoursesincombo no longer affects whether the combo list is displayed. Setting is deprecated.
        unset_config('numcoursesincombo');
        upgrade_main_savepoint(true, 2013041600.0);
    }
    if ($oldversion < 2013041601.0) {
        // Create a new 'badge_external' table first.
        // Define table 'badge_external' to be created.
        $table = new xmldb_table('badge_external');
        // Adding fields to table 'badge_external'.
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null);
        $table->add_field('backpackid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, 'id');
        $table->add_field('collectionid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, 'backpackid');
        // Adding keys to table 'badge_external'.
        $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->add_key('fk_backpackid', XMLDB_KEY_FOREIGN, array('backpackid'), 'badge_backpack', array('id'));
        // Conditionally launch create table for 'badge_external'.
        if (!$dbman->table_exists($table)) {
            $dbman->create_table($table);
        }
        // Perform user data migration.
        $usercollections = $DB->get_records('badge_backpack');
        foreach ($usercollections as $usercollection) {
            $collection = new stdClass();
            $collection->backpackid = $usercollection->id;
            $collection->collectionid = $usercollection->backpackgid;
            $DB->insert_record('badge_external', $collection);
        }
        // Finally, drop the column.
        // Define field backpackgid to be dropped from 'badge_backpack'.
        $table = new xmldb_table('badge_backpack');
        $field = new xmldb_field('backpackgid');
        // Conditionally launch drop field backpackgid.
        if ($dbman->field_exists($table, $field)) {
            $dbman->drop_field($table, $field);
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2013041601.0);
    }
    if ($oldversion < 2013041601.01) {
        // Changing the default of field descriptionformat on table user to 1.
        $table = new xmldb_table('user');
        $field = new xmldb_field('descriptionformat', XMLDB_TYPE_INTEGER, '2', null, XMLDB_NOTNULL, null, '1', 'description');
        // Launch change of default for field descriptionformat.
        $dbman->change_field_default($table, $field);
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2013041601.01);
    }
    if ($oldversion < 2013041900.0) {
        require_once $CFG->dirroot . '/cache/locallib.php';
        // The features bin needs updating.
        cache_config_writer::update_default_config_stores();
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2013041900.0);
    }
    if ($oldversion < 2013042300.0) {
        // Adding index to unreadmessageid field of message_working table (MDL-34933)
        $table = new xmldb_table('message_working');
        $index = new xmldb_index('unreadmessageid_idx', XMLDB_INDEX_NOTUNIQUE, array('unreadmessageid'));
        // Conditionally launch add index unreadmessageid
        if (!$dbman->index_exists($table, $index)) {
            $dbman->add_index($table, $index);
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2013042300.0);
    }
    // Moodle v2.5.0 release upgrade line.
    // Put any upgrade step following this.
    if ($oldversion < 2013051400.01) {
        // Fix incorrect cc-nc url. Unfortunately the license 'plugins' do
        // not give a mechanism to do this.
        $sql = "UPDATE {license}\n                   SET source = :url, version = :newversion\n                 WHERE shortname = :shortname AND version = :oldversion";
        $params = array('url' => 'http://creativecommons.org/licenses/by-nc/3.0/', 'shortname' => 'cc-nc', 'newversion' => '2013051500', 'oldversion' => '2010033100');
        $DB->execute($sql, $params);
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2013051400.01);
    }
    if ($oldversion < 2013061400.01) {
        // Clean up old tokens which haven't been deleted.
        $DB->execute("DELETE FROM {user_private_key} WHERE NOT EXISTS\n                         (SELECT 'x' FROM {user} WHERE deleted = 0 AND id = userid)");
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2013061400.01);
    }
    if ($oldversion < 2013061700.0) {
        // MDL-40103: Remove unused template tables from the database.
        // These are now created inline with xmldb_table.
        $tablestocleanup = array('temp_enroled_template', 'temp_log_template', 'backup_files_template', 'backup_ids_template');
        $dbman = $DB->get_manager();
        foreach ($tablestocleanup as $table) {
            $xmltable = new xmldb_table($table);
            if ($dbman->table_exists($xmltable)) {
                $dbman->drop_table($xmltable);
            }
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2013061700.0);
    }
    if ($oldversion < 2013070800.0) {
        // Remove orphan repository instances.
        if ($DB->get_dbfamily() === 'mysql') {
            $sql = "DELETE {repository_instances} FROM {repository_instances}\n                    LEFT JOIN {context} ON {context}.id = {repository_instances}.contextid\n                    WHERE {context}.id IS NULL";
        } else {
            $sql = "DELETE FROM {repository_instances}\n                    WHERE NOT EXISTS (\n                        SELECT 'x' FROM {context}\n                        WHERE {context}.id = {repository_instances}.contextid)";
        }
        $DB->execute($sql);
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2013070800.0);
    }
    if ($oldversion < 2013070800.01) {
        // Define field lastnamephonetic to be added to user.
        $table = new xmldb_table('user');
        $field = new xmldb_field('lastnamephonetic', XMLDB_TYPE_CHAR, '255', null, null, null, null, 'imagealt');
        $index = new xmldb_index('lastnamephonetic', XMLDB_INDEX_NOTUNIQUE, array('lastnamephonetic'));
        // Conditionally launch add field lastnamephonetic.
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
            $dbman->add_index($table, $index);
        }
        // Define field firstnamephonetic to be added to user.
        $table = new xmldb_table('user');
        $field = new xmldb_field('firstnamephonetic', XMLDB_TYPE_CHAR, '255', null, null, null, null, 'lastnamephonetic');
        $index = new xmldb_index('firstnamephonetic', XMLDB_INDEX_NOTUNIQUE, array('firstnamephonetic'));
        // Conditionally launch add field firstnamephonetic.
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
            $dbman->add_index($table, $index);
        }
        // Define field alternatename to be added to user.
        $table = new xmldb_table('user');
        $field = new xmldb_field('middlename', XMLDB_TYPE_CHAR, '255', null, null, null, null, 'firstnamephonetic');
        $index = new xmldb_index('middlename', XMLDB_INDEX_NOTUNIQUE, array('middlename'));
        // Conditionally launch add field firstnamephonetic.
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
            $dbman->add_index($table, $index);
        }
        // Define field alternatename to be added to user.
        $table = new xmldb_table('user');
        $field = new xmldb_field('alternatename', XMLDB_TYPE_CHAR, '255', null, null, null, null, 'middlename');
        $index = new xmldb_index('alternatename', XMLDB_INDEX_NOTUNIQUE, array('alternatename'));
        // Conditionally launch add field alternatename.
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
            $dbman->add_index($table, $index);
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2013070800.01);
    }
    if ($oldversion < 2013071500.01) {
        // The enrol_authorize plugin has been removed, if there are no records
        // and no plugin files then remove the plugin data.
        $enrolauthorize = new xmldb_table('enrol_authorize');
        $enrolauthorizerefunds = new xmldb_table('enrol_authorize_refunds');
        if (!file_exists($CFG->dirroot . '/enrol/authorize/version.php') && $dbman->table_exists($enrolauthorize) && $dbman->table_exists($enrolauthorizerefunds)) {
            $enrolauthorizecount = $DB->count_records('enrol_authorize');
            $enrolauthorizerefundcount = $DB->count_records('enrol_authorize_refunds');
            if (empty($enrolauthorizecount) && empty($enrolauthorizerefundcount)) {
                // Drop the database tables.
                $dbman->drop_table($enrolauthorize);
                $dbman->drop_table($enrolauthorizerefunds);
                // Drop the message provider and associated data manually.
                $DB->delete_records('message_providers', array('component' => 'enrol_authorize'));
                $DB->delete_records_select('config_plugins', "plugin = 'message' AND " . $DB->sql_like('name', '?', false), array("%_provider_enrol_authorize_%"));
                $DB->delete_records_select('user_preferences', $DB->sql_like('name', '?', false), array("message_provider_enrol_authorize_%"));
                // Remove capabilities.
                capabilities_cleanup('enrol_authorize');
                // Remove all other associated config.
                unset_all_config_for_plugin('enrol_authorize');
            }
        }
        upgrade_main_savepoint(true, 2013071500.01);
    }
    if ($oldversion < 2013071500.02) {
        // Define field attachment to be dropped from badge.
        $table = new xmldb_table('badge');
        $field = new xmldb_field('image');
        // Conditionally launch drop field eventtype.
        if ($dbman->field_exists($table, $field)) {
            $dbman->drop_field($table, $field);
        }
        upgrade_main_savepoint(true, 2013071500.02);
    }
    if ($oldversion < 2013072600.01) {
        upgrade_mssql_nvarcharmax();
        upgrade_mssql_varbinarymax();
        upgrade_main_savepoint(true, 2013072600.01);
    }
    if ($oldversion < 2013081200.0) {
        // Define field uploadfiles to be added to external_services.
        $table = new xmldb_table('external_services');
        $field = new xmldb_field('uploadfiles', XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, '0', 'downloadfiles');
        // Conditionally launch add field uploadfiles.
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2013081200.0);
    }
    if ($oldversion < 2013082300.01) {
        // Define the table 'backup_logs' and the field 'message' which we will be changing from a char to a text field.
        $table = new xmldb_table('backup_logs');
        $field = new xmldb_field('message', XMLDB_TYPE_TEXT, null, null, XMLDB_NOTNULL, null, null, 'loglevel');
        // Perform the change.
        $dbman->change_field_type($table, $field);
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2013082300.01);
    }
    // Convert SCORM course format courses to singleactivity.
    if ($oldversion < 2013082700.0) {
        // First set relevant singleactivity settings.
        $formatoptions = new stdClass();
        $formatoptions->format = 'singleactivity';
        $formatoptions->sectionid = 0;
        $formatoptions->name = 'activitytype';
        $formatoptions->value = 'scorm';
        $courses = $DB->get_recordset('course', array('format' => 'scorm'), 'id');
        foreach ($courses as $course) {
            $formatoptions->courseid = $course->id;
            $DB->insert_record('course_format_options', $formatoptions);
        }
        $courses->close();
        // Now update course format for these courses.
        $sql = "UPDATE {course}\n                   SET format = 'singleactivity', modinfo = '', sectioncache = ''\n                 WHERE format = 'scorm'";
        $DB->execute($sql);
        upgrade_main_savepoint(true, 2013082700.0);
    }
    if ($oldversion < 2013090500.01) {
        // Define field calendartype to be added to course.
        $table = new xmldb_table('course');
        $field = new xmldb_field('calendartype', XMLDB_TYPE_CHAR, '30', null, XMLDB_NOTNULL, null, null);
        // Conditionally launch add field calendartype.
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        // Since structure of 'course' table has changed we need to re-read $SITE from DB.
        $SITE = $DB->get_record('course', array('id' => $SITE->id));
        $COURSE = clone $SITE;
        // Define field calendartype to be added to user.
        $table = new xmldb_table('user');
        $field = new xmldb_field('calendartype', XMLDB_TYPE_CHAR, '30', null, XMLDB_NOTNULL, null, 'gregorian');
        // Conditionally launch add field calendartype.
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2013090500.01);
    }
    if ($oldversion < 2013091000.02) {
        // Define field cacherev to be added to course.
        $table = new xmldb_table('course');
        $field = new xmldb_field('cacherev', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0', 'completionnotify');
        // Conditionally launch add field cacherev.
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        // Since structure of 'course' table has changed we need to re-read $SITE from DB.
        $SITE = $DB->get_record('course', array('id' => $SITE->id));
        $COURSE = clone $SITE;
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2013091000.02);
    }
    if ($oldversion < 2013091000.03) {
        // Define field modinfo to be dropped from course.
        $table = new xmldb_table('course');
        $field = new xmldb_field('modinfo');
        // Conditionally launch drop field modinfo.
        if ($dbman->field_exists($table, $field)) {
            $dbman->drop_field($table, $field);
        }
        // Define field sectioncache to be dropped from course.
        $field = new xmldb_field('sectioncache');
        // Conditionally launch drop field sectioncache.
        if ($dbman->field_exists($table, $field)) {
            $dbman->drop_field($table, $field);
        }
        // Since structure of 'course' table has changed we need to re-read $SITE from DB.
        $SITE = $DB->get_record('course', array('id' => $SITE->id));
        $COURSE = clone $SITE;
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2013091000.03);
    }
    if ($oldversion < 2013091300.01) {
        $table = new xmldb_table('user');
        // Changing precision of field institution on table user to (255).
        $field = new xmldb_field('institution', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, 'phone2');
        // Launch change of precision for field institution.
        $dbman->change_field_precision($table, $field);
        // Changing precision of field department on table user to (255).
        $field = new xmldb_field('department', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, 'institution');
        // Launch change of precision for field department.
        $dbman->change_field_precision($table, $field);
        // Changing precision of field address on table user to (255).
        $field = new xmldb_field('address', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, 'department');
        // Launch change of precision for field address.
        $dbman->change_field_precision($table, $field);
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2013091300.01);
    }
    if ($oldversion < 2013092000.01) {
        // Define table question_statistics to be created.
        $table = new xmldb_table('question_statistics');
        // Adding fields to table question_statistics.
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
        $table->add_field('hashcode', XMLDB_TYPE_CHAR, '40', null, XMLDB_NOTNULL, null, null);
        $table->add_field('timemodified', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null);
        $table->add_field('questionid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null);
        $table->add_field('slot', XMLDB_TYPE_INTEGER, '10', null, null, null, null);
        $table->add_field('subquestion', XMLDB_TYPE_INTEGER, '4', null, XMLDB_NOTNULL, null, null);
        $table->add_field('s', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
        $table->add_field('effectiveweight', XMLDB_TYPE_NUMBER, '15, 5', null, null, null, null);
        $table->add_field('negcovar', XMLDB_TYPE_INTEGER, '2', null, XMLDB_NOTNULL, null, '0');
        $table->add_field('discriminationindex', XMLDB_TYPE_NUMBER, '15, 5', null, null, null, null);
        $table->add_field('discriminativeefficiency', XMLDB_TYPE_NUMBER, '15, 5', null, null, null, null);
        $table->add_field('sd', XMLDB_TYPE_NUMBER, '15, 10', null, null, null, null);
        $table->add_field('facility', XMLDB_TYPE_NUMBER, '15, 10', null, null, null, null);
        $table->add_field('subquestions', XMLDB_TYPE_TEXT, null, null, null, null, null);
        $table->add_field('maxmark', XMLDB_TYPE_NUMBER, '12, 7', null, null, null, null);
        $table->add_field('positions', XMLDB_TYPE_TEXT, null, null, null, null, null);
        $table->add_field('randomguessscore', XMLDB_TYPE_NUMBER, '12, 7', null, null, null, null);
        // Adding keys to table question_statistics.
        $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
        // Conditionally launch create table for question_statistics.
        if (!$dbman->table_exists($table)) {
            $dbman->create_table($table);
        }
        // Define table question_response_analysis to be created.
        $table = new xmldb_table('question_response_analysis');
        // Adding fields to table question_response_analysis.
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
        $table->add_field('hashcode', XMLDB_TYPE_CHAR, '40', null, XMLDB_NOTNULL, null, null);
        $table->add_field('timemodified', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null);
        $table->add_field('questionid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null);
        $table->add_field('subqid', XMLDB_TYPE_CHAR, '100', null, XMLDB_NOTNULL, null, null);
        $table->add_field('aid', XMLDB_TYPE_CHAR, '100', null, null, null, null);
        $table->add_field('response', XMLDB_TYPE_TEXT, null, null, null, null, null);
        $table->add_field('rcount', XMLDB_TYPE_INTEGER, '10', null, null, null, null);
        $table->add_field('credit', XMLDB_TYPE_NUMBER, '15, 5', null, XMLDB_NOTNULL, null, null);
        // Adding keys to table question_response_analysis.
        $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
        // Conditionally launch create table for question_response_analysis.
        if (!$dbman->table_exists($table)) {
            $dbman->create_table($table);
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2013092000.01);
    }
    if ($oldversion < 2013092001.01) {
        // Force uninstall of deleted tool.
        if (!file_exists("{$CFG->dirroot}/{$CFG->admin}/tool/bloglevelupgrade")) {
            // Remove capabilities.
            capabilities_cleanup('tool_bloglevelupgrade');
            // Remove all other associated config.
            unset_all_config_for_plugin('tool_bloglevelupgrade');
        }
        upgrade_main_savepoint(true, 2013092001.01);
    }
    if ($oldversion < 2013092001.02) {
        // Define field version to be dropped from modules.
        $table = new xmldb_table('modules');
        $field = new xmldb_field('version');
        // Conditionally launch drop field version.
        if ($dbman->field_exists($table, $field)) {
            // Migrate all plugin version info to config_plugins table.
            $modules = $DB->get_records('modules');
            foreach ($modules as $module) {
                set_config('version', $module->version, 'mod_' . $module->name);
            }
            unset($modules);
            $dbman->drop_field($table, $field);
        }
        // Define field version to be dropped from block.
        $table = new xmldb_table('block');
        $field = new xmldb_field('version');
        // Conditionally launch drop field version.
        if ($dbman->field_exists($table, $field)) {
            $blocks = $DB->get_records('block');
            foreach ($blocks as $block) {
                set_config('version', $block->version, 'block_' . $block->name);
            }
            unset($blocks);
            $dbman->drop_field($table, $field);
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2013092001.02);
    }
    if ($oldversion < 2013092700.01) {
        $table = new xmldb_table('files');
        // Define field referencelastsync to be dropped from files.
        $field = new xmldb_field('referencelastsync');
        // Conditionally launch drop field referencelastsync.
        if ($dbman->field_exists($table, $field)) {
            $dbman->drop_field($table, $field);
        }
        // Define field referencelifetime to be dropped from files.
        $field = new xmldb_field('referencelifetime');
        // Conditionally launch drop field referencelifetime.
        if ($dbman->field_exists($table, $field)) {
            $dbman->drop_field($table, $field);
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2013092700.01);
    }
    if ($oldversion < 2013100400.01) {
        // Add user_devices core table.
        // Define field id to be added to user_devices.
        $table = new xmldb_table('user_devices');
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null);
        $table->add_field('userid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0', 'id');
        $table->add_field('appid', XMLDB_TYPE_CHAR, '128', null, XMLDB_NOTNULL, null, null, 'userid');
        $table->add_field('name', XMLDB_TYPE_CHAR, '32', null, XMLDB_NOTNULL, null, null, 'appid');
        $table->add_field('model', XMLDB_TYPE_CHAR, '32', null, XMLDB_NOTNULL, null, null, 'name');
        $table->add_field('platform', XMLDB_TYPE_CHAR, '32', null, XMLDB_NOTNULL, null, null, 'model');
        $table->add_field('version', XMLDB_TYPE_CHAR, '32', null, XMLDB_NOTNULL, null, null, 'platform');
        $table->add_field('pushid', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, 'version');
        $table->add_field('uuid', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, 'pushid');
        $table->add_field('timecreated', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, 'uuid');
        $table->add_field('timemodified', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, 'timecreated');
        $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->add_key('pushid-userid', XMLDB_KEY_UNIQUE, array('pushid', 'userid'));
        $table->add_key('pushid-platform', XMLDB_KEY_UNIQUE, array('pushid', 'platform'));
        $table->add_key('userid', XMLDB_KEY_FOREIGN, array('userid'), 'user', array('id'));
        if (!$dbman->table_exists($table)) {
            $dbman->create_table($table);
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2013100400.01);
    }
    if ($oldversion < 2013100800.0) {
        // Define field maxfraction to be added to question_attempts.
        $table = new xmldb_table('question_attempts');
        $field = new xmldb_field('maxfraction', XMLDB_TYPE_NUMBER, '12, 7', null, XMLDB_NOTNULL, null, '1', 'minfraction');
        // Conditionally launch add field maxfraction.
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2013100800.0);
    }
    if ($oldversion < 2013100800.01) {
        // Create a new 'user_password_resets' table.
        $table = new xmldb_table('user_password_resets');
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null);
        $table->add_field('userid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null);
        $table->add_field('timerequested', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null);
        $table->add_field('timererequested', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, 0, null);
        $table->add_field('token', XMLDB_TYPE_CHAR, '32', null, XMLDB_NOTNULL, null, null, null);
        // Adding keys to table.
        $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->add_key('fk_userid', XMLDB_KEY_FOREIGN, array('userid'), 'user', array('id'));
        // Conditionally launch create table.
        if (!$dbman->table_exists($table)) {
            $dbman->create_table($table);
        }
        upgrade_main_savepoint(true, 2013100800.01);
    }
    if ($oldversion < 2013100800.02) {
        $sql = "INSERT INTO {user_preferences}(userid, name, value)\n                SELECT id, 'htmleditor', 'textarea' FROM {user} u where u.htmleditor = 0";
        $DB->execute($sql);
        // Define field htmleditor to be dropped from user
        $table = new xmldb_table('user');
        $field = new xmldb_field('htmleditor');
        // Conditionally launch drop field requested
        if ($dbman->field_exists($table, $field)) {
            $dbman->drop_field($table, $field);
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2013100800.02);
    }
    if ($oldversion < 2013100900.0) {
        // Define field lifetime to be dropped from files_reference.
        $table = new xmldb_table('files_reference');
        $field = new xmldb_field('lifetime');
        // Conditionally launch drop field lifetime.
        if ($dbman->field_exists($table, $field)) {
            $dbman->drop_field($table, $field);
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2013100900.0);
    }
    if ($oldversion < 2013100901.0) {
        // Fixing possible wrong MIME type for Java Network Launch Protocol (JNLP) files.
        $select = $DB->sql_like('filename', '?', false);
        $DB->set_field_select('files', 'mimetype', 'application/x-java-jnlp-file', $select, array('%.jnlp'));
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2013100901.0);
    }
    if ($oldversion < 2013102100.0) {
        // Changing default value for the status of a course backup.
        $table = new xmldb_table('backup_courses');
        $field = new xmldb_field('laststatus', XMLDB_TYPE_CHAR, '1', null, XMLDB_NOTNULL, null, '5', 'lastendtime');
        // Launch change of precision for field value
        $dbman->change_field_precision($table, $field);
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2013102100.0);
    }
    if ($oldversion < 2013102201.0) {
        $params = array('plugin' => 'editor_atto', 'name' => 'version');
        $attoversion = $DB->get_record('config_plugins', $params, 'value', IGNORE_MISSING);
        if ($attoversion) {
            $attoversion = floatval($attoversion->value);
        }
        // Only these versions that were part of 2.6 beta should be removed.
        // Manually installed versions of 2.5 - or later releases for 2.6 installed
        // via the plugins DB should not be uninstalled.
        if ($attoversion && $attoversion > 2013051500.0 && $attoversion < 2013102201.0) {
            // Remove all other associated config.
            unset_all_config_for_plugin('editor_atto');
            unset_all_config_for_plugin('atto_bold');
            unset_all_config_for_plugin('atto_clear');
            unset_all_config_for_plugin('atto_html');
            unset_all_config_for_plugin('atto_image');
            unset_all_config_for_plugin('atto_indent');
            unset_all_config_for_plugin('atto_italic');
            unset_all_config_for_plugin('atto_link');
            unset_all_config_for_plugin('atto_media');
            unset_all_config_for_plugin('atto_orderedlist');
            unset_all_config_for_plugin('atto_outdent');
            unset_all_config_for_plugin('atto_strike');
            unset_all_config_for_plugin('atto_title');
            unset_all_config_for_plugin('atto_underline');
            unset_all_config_for_plugin('atto_unlink');
            unset_all_config_for_plugin('atto_unorderedlist');
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2013102201.0);
    }
    if ($oldversion < 2013102500.01) {
        // Find all fileareas that have missing root folder entry and add the root folder entry.
        if (empty($CFG->filesrootrecordsfixed)) {
            upgrade_fix_missing_root_folders();
            // To skip running the same script on the upgrade to the next major release.
            set_config('filesrootrecordsfixed', 1);
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2013102500.01);
    }
    if ($oldversion < 2013110500.01) {
        // MDL-38228. Corrected course_modules upgrade script instead of 2013021801.01.
        // This upgrade script fixes the mismatches between DB fields course_modules.section
        // and course_sections.sequence. It makes sure that each module is included
        // in the sequence of at least one section.
        // There is also a separate script for admins: admin/cli/fix_course_sortorder.php
        // This script in included in each major version upgrade process so make sure we don't run it twice.
        if (empty($CFG->movingmoduleupgradescriptwasrun)) {
            upgrade_course_modules_sequences();
            // To skip running the same script on the upgrade to the next major release.
            set_config('movingmoduleupgradescriptwasrun', 1);
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2013110500.01);
    }
    if ($oldversion < 2013110600.01) {
        if (!file_exists($CFG->dirroot . '/theme/mymobile')) {
            // Replace the mymobile settings.
            $DB->set_field('course', 'theme', 'clean', array('theme' => 'mymobile'));
            $DB->set_field('course_categories', 'theme', 'clean', array('theme' => 'mymobile'));
            $DB->set_field('user', 'theme', 'clean', array('theme' => 'mymobile'));
            $DB->set_field('mnet_host', 'theme', 'clean', array('theme' => 'mymobile'));
            // Replace the theme configs.
            if (get_config('core', 'theme') === 'mymobile') {
                set_config('theme', 'clean');
            }
            if (get_config('core', 'thememobile') === 'mymobile') {
                set_config('thememobile', 'clean');
            }
            if (get_config('core', 'themelegacy') === 'mymobile') {
                set_config('themelegacy', 'clean');
            }
            if (get_config('core', 'themetablet') === 'mymobile') {
                set_config('themetablet', 'clean');
            }
            // Hacky emulation of plugin uninstallation.
            unset_all_config_for_plugin('theme_mymobile');
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2013110600.01);
    }
    if ($oldversion < 2013110600.02) {
        // If the user is logged in, we ensure that the alternate name fields are present
        // in the session. It will not be the case when upgrading from 2.5 downwards.
        if (!empty($USER->id)) {
            $refreshuser = $DB->get_record('user', array('id' => $USER->id));
            $fields = array('firstnamephonetic', 'lastnamephonetic', 'middlename', 'alternatename', 'firstname', 'lastname');
            foreach ($fields as $field) {
                $USER->{$field} = $refreshuser->{$field};
            }
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2013110600.02);
    }
    // Moodle v2.6.0 release upgrade line.
    // Put any upgrade step following this.
    if ($oldversion < 2013111800.01) {
        // Delete notes of deleted courses.
        $sql = "DELETE FROM {post}\n                 WHERE NOT EXISTS (SELECT {course}.id FROM {course}\n                                    WHERE {course}.id = {post}.courseid)\n                       AND {post}.module = ?";
        $DB->execute($sql, array('notes'));
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2013111800.01);
    }
    if ($oldversion < 2013122400.01) {
        // Purge stored passwords from config_log table, ideally this should be in each plugin
        // but that would complicate backporting...
        $items = array('core/cronremotepassword', 'core/proxypassword', 'core/smtppass', 'core/jabberpassword', 'enrol_database/dbpass', 'enrol_ldap/bind_pw', 'url/secretphrase');
        foreach ($items as $item) {
            list($plugin, $name) = explode('/', $item);
            $sqlcomparevalue = $DB->sql_compare_text('value');
            $sqlcompareoldvalue = $DB->sql_compare_text('oldvalue');
            if ($plugin === 'core') {
                $sql = "UPDATE {config_log}\n                           SET value = :value\n                         WHERE name = :name AND plugin IS NULL AND {$sqlcomparevalue} <> :empty";
                $params = array('value' => '********', 'name' => $name, 'empty' => '');
                $DB->execute($sql, $params);
                $sql = "UPDATE {config_log}\n                           SET oldvalue = :value\n                         WHERE name = :name AND plugin IS NULL AND {$sqlcompareoldvalue} <> :empty";
                $params = array('value' => '********', 'name' => $name, 'empty' => '');
                $DB->execute($sql, $params);
            } else {
                $sql = "UPDATE {config_log}\n                           SET value = :value\n                         WHERE name = :name AND plugin = :plugin AND {$sqlcomparevalue} <> :empty";
                $params = array('value' => '********', 'name' => $name, 'plugin' => $plugin, 'empty' => '');
                $DB->execute($sql, $params);
                $sql = "UPDATE {config_log}\n                           SET oldvalue = :value\n                         WHERE name = :name AND plugin = :plugin AND  {$sqlcompareoldvalue} <> :empty";
                $params = array('value' => '********', 'name' => $name, 'plugin' => $plugin, 'empty' => '');
                $DB->execute($sql, $params);
            }
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2013122400.01);
    }
    if ($oldversion < 2014011000.01) {
        // Define table cache_text to be dropped.
        $table = new xmldb_table('cache_text');
        // Conditionally launch drop table for cache_text.
        if ($dbman->table_exists($table)) {
            $dbman->drop_table($table);
        }
        unset_config('cachetext');
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2014011000.01);
    }
    if ($oldversion < 2014011701.0) {
        // Fix gradebook sortorder duplicates.
        upgrade_grade_item_fix_sortorder();
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2014011701.0);
    }
    if ($oldversion < 2014012300.01) {
        // Remove deleted users home pages.
        $sql = "DELETE FROM {my_pages}\n                WHERE EXISTS (SELECT {user}.id\n                                  FROM {user}\n                                  WHERE {user}.id = {my_pages}.userid\n                                  AND {user}.deleted = 1)\n                AND {my_pages}.private = 1";
        $DB->execute($sql);
        // Reached main savepoint.
        upgrade_main_savepoint(true, 2014012300.01);
    }
    if ($oldversion < 2014012400.0) {
        // Define table lock_db to be created.
        $table = new xmldb_table('lock_db');
        // Adding fields to table lock_db.
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
        $table->add_field('resourcekey', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null);
        $table->add_field('expires', XMLDB_TYPE_INTEGER, '10', null, null, null, null);
        $table->add_field('owner', XMLDB_TYPE_CHAR, '36', null, null, null, null);
        // Adding keys to table lock_db.
        $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
        // Adding indexes to table lock_db.
        $table->add_index('resourcekey_uniq', XMLDB_INDEX_UNIQUE, array('resourcekey'));
        $table->add_index('expires_idx', XMLDB_INDEX_NOTUNIQUE, array('expires'));
        $table->add_index('owner_idx', XMLDB_INDEX_NOTUNIQUE, array('owner'));
        // Conditionally launch create table for lock_db.
        if (!$dbman->table_exists($table)) {
            $dbman->create_table($table);
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2014012400.0);
    }
    if ($oldversion < 2014021300.01) {
        // Delete any cached stats to force recalculation later, then we can be sure that cached records will have the correct
        // field.
        $DB->delete_records('question_response_analysis');
        $DB->delete_records('question_statistics');
        $DB->delete_records('quiz_statistics');
        // Define field variant to be added to question_statistics.
        $table = new xmldb_table('question_statistics');
        $field = new xmldb_field('variant', XMLDB_TYPE_INTEGER, '10', null, null, null, null, 'subquestion');
        // Conditionally launch add field variant.
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2014021300.01);
    }
    if ($oldversion < 2014021300.02) {
        // Define field variant to be added to question_response_analysis.
        $table = new xmldb_table('question_response_analysis');
        $field = new xmldb_field('variant', XMLDB_TYPE_INTEGER, '10', null, null, null, null, 'questionid');
        // Conditionally launch add field variant.
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2014021300.02);
    }
    if ($oldversion < 2014021800.0) {
        // Define field queued to be added to portfolio_tempdata.
        $table = new xmldb_table('portfolio_tempdata');
        $field = new xmldb_field('queued', XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, '0', 'instance');
        // Conditionally launch add field queued.
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2014021800.0);
    }
    if ($oldversion < 2014021900.01) {
        // Force uninstall of deleted tool.
        // Normally, in this sort of situation, we would do a file_exists check,
        // in case the plugin had been added back as an add-on. However, this
        // plugin is completely useless after Moodle 2.6, so we check that the
        // files have been removed in upgrade_stale_php_files_present, and we
        // uninstall it unconditionally here.
        // Remove all associated config.
        unset_all_config_for_plugin('tool_qeupgradehelper');
        upgrade_main_savepoint(true, 2014021900.01);
    }
    if ($oldversion < 2014021900.02) {
        // Define table question_states to be dropped.
        $table = new xmldb_table('question_states');
        // Conditionally launch drop table for question_states.
        if ($dbman->table_exists($table)) {
            $dbman->drop_table($table);
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2014021900.02);
    }
    if ($oldversion < 2014021900.03) {
        // Define table question_sessions to be dropped.
        $table = new xmldb_table('question_sessions');
        // Conditionally launch drop table for question_sessions.
        if ($dbman->table_exists($table)) {
            $dbman->drop_table($table);
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2014021900.03);
    }
    if ($oldversion < 2014022600.0) {
        $table = new xmldb_table('task_scheduled');
        // Adding fields to table task_scheduled.
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
        $table->add_field('component', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null);
        $table->add_field('classname', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null);
        $table->add_field('lastruntime', XMLDB_TYPE_INTEGER, '10', null, null, null, null);
        $table->add_field('nextruntime', XMLDB_TYPE_INTEGER, '10', null, null, null, null);
        $table->add_field('blocking', XMLDB_TYPE_INTEGER, '2', null, XMLDB_NOTNULL, null, '0');
        $table->add_field('minute', XMLDB_TYPE_CHAR, '25', null, XMLDB_NOTNULL, null, null);
        $table->add_field('hour', XMLDB_TYPE_CHAR, '25', null, XMLDB_NOTNULL, null, null);
        $table->add_field('day', XMLDB_TYPE_CHAR, '25', null, XMLDB_NOTNULL, null, null);
        $table->add_field('month', XMLDB_TYPE_CHAR, '25', null, XMLDB_NOTNULL, null, null);
        $table->add_field('dayofweek', XMLDB_TYPE_CHAR, '25', null, XMLDB_NOTNULL, null, null);
        $table->add_field('faildelay', XMLDB_TYPE_INTEGER, '10', null, null, null, null);
        $table->add_field('customised', XMLDB_TYPE_INTEGER, '2', null, XMLDB_NOTNULL, null, '0');
        $table->add_field('disabled', XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, '0');
        // Adding keys to table task_scheduled.
        $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
        // Adding indexes to table task_scheduled.
        $table->add_index('classname_uniq', XMLDB_INDEX_UNIQUE, array('classname'));
        // Conditionally launch create table for task_scheduled.
        if (!$dbman->table_exists($table)) {
            $dbman->create_table($table);
        }
        // Define table task_adhoc to be created.
        $table = new xmldb_table('task_adhoc');
        // Adding fields to table task_adhoc.
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
        $table->add_field('component', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null);
        $table->add_field('classname', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null);
        $table->add_field('nextruntime', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null);
        $table->add_field('faildelay', XMLDB_TYPE_INTEGER, '10', null, null, null, null);
        $table->add_field('customdata', XMLDB_TYPE_TEXT, null, null, null, null, null);
        $table->add_field('blocking', XMLDB_TYPE_INTEGER, '2', null, XMLDB_NOTNULL, null, '0');
        // Adding keys to table task_adhoc.
        $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
        // Adding indexes to table task_adhoc.
        $table->add_index('nextruntime_idx', XMLDB_INDEX_NOTUNIQUE, array('nextruntime'));
        // Conditionally launch create table for task_adhoc.
        if (!$dbman->table_exists($table)) {
            $dbman->create_table($table);
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2014022600.0);
    }
    if ($oldversion < 2014031400.02) {
        // Delete any cached stats to force recalculation later, then we can be sure that cached records will have the correct
        // field.
        $DB->delete_records('question_response_analysis');
        $DB->delete_records('question_statistics');
        $DB->delete_records('quiz_statistics');
        // Define field response to be dropped from question_response_analysis.
        $table = new xmldb_table('question_response_analysis');
        $field = new xmldb_field('rcount');
        // Conditionally launch drop field response.
        if ($dbman->field_exists($table, $field)) {
            $dbman->drop_field($table, $field);
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2014031400.02);
    }
    if ($oldversion < 2014031400.03) {
        // Define table question_response_count to be created.
        $table = new xmldb_table('question_response_count');
        // Adding fields to table question_response_count.
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
        $table->add_field('analysisid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null);
        $table->add_field('try', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null);
        $table->add_field('rcount', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null);
        // Adding keys to table question_response_count.
        $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->add_key('analysisid', XMLDB_KEY_FOREIGN, array('analysisid'), 'question_response_analysis', array('id'));
        // Conditionally launch create table for question_response_count.
        if (!$dbman->table_exists($table)) {
            $dbman->create_table($table);
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2014031400.03);
    }
    if ($oldversion < 2014031400.04) {
        // Define field whichtries to be added to question_response_analysis.
        $table = new xmldb_table('question_response_analysis');
        $field = new xmldb_field('whichtries', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, 'hashcode');
        // Conditionally launch add field whichtries.
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2014031400.04);
    }
    if ($oldversion < 2014032600.0) {
        // Removing the themes from core.
        $themes = array('afterburner', 'anomaly', 'arialist', 'binarius', 'boxxie', 'brick', 'formal_white', 'formfactor', 'fusion', 'leatherbound', 'magazine', 'nimble', 'nonzero', 'overlay', 'serenity', 'sky_high', 'splash', 'standard', 'standardold');
        foreach ($themes as $key => $theme) {
            if (check_dir_exists($CFG->dirroot . '/theme/' . $theme, false)) {
                // Ignore the themes that have been re-downloaded.
                unset($themes[$key]);
            }
        }
        // Check we actually have themes to remove.
        if (count($themes) > 0) {
            // Replace the theme configs.
            if (in_array(get_config('core', 'theme'), $themes)) {
                set_config('theme', 'clean');
            }
            if (in_array(get_config('core', 'thememobile'), $themes)) {
                set_config('thememobile', 'clean');
            }
            if (in_array(get_config('core', 'themelegacy'), $themes)) {
                set_config('themelegacy', 'clean');
            }
            if (in_array(get_config('core', 'themetablet'), $themes)) {
                set_config('themetablet', 'clean');
            }
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2014032600.0);
    }
    if ($oldversion < 2014032600.02) {
        // Add new fields to the 'tag_instance' table.
        $table = new xmldb_table('tag_instance');
        $field = new xmldb_field('component', XMLDB_TYPE_CHAR, '100', null, false, null, null, 'tagid');
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        $field = new xmldb_field('contextid', XMLDB_TYPE_INTEGER, '10', null, false, null, null, 'itemid');
        // Define the 'contextid' foreign key to be added to the tag_instance table.
        $key = new xmldb_key('contextid', XMLDB_KEY_FOREIGN, array('contextid'), 'context', array('id'));
        if ($dbman->field_exists($table, $field)) {
            $dbman->drop_key($table, $key);
            $DB->set_field('tag_instance', 'contextid', null, array('contextid' => 0));
            $dbman->change_field_default($table, $field);
        } else {
            $dbman->add_field($table, $field);
        }
        $dbman->add_key($table, $key);
        $field = new xmldb_field('timecreated', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0', 'ordering');
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        $sql = "UPDATE {tag_instance}\n                   SET timecreated = timemodified";
        $DB->execute($sql);
        // Update all the course tags.
        $sql = "UPDATE {tag_instance}\n                   SET component = 'core',\n                       contextid = (SELECT ctx.id\n                                      FROM {context} ctx\n                                     WHERE ctx.contextlevel = :contextlevel\n                                       AND ctx.instanceid = {tag_instance}.itemid)\n                 WHERE itemtype = 'course' AND contextid IS NULL";
        $DB->execute($sql, array('contextlevel' => CONTEXT_COURSE));
        // Update all the user tags.
        $sql = "UPDATE {tag_instance}\n                   SET component = 'core',\n                       contextid = (SELECT ctx.id\n                                      FROM {context} ctx\n                                     WHERE ctx.contextlevel = :contextlevel\n                                       AND ctx.instanceid = {tag_instance}.itemid)\n                 WHERE itemtype = 'user' AND contextid IS NULL";
        $DB->execute($sql, array('contextlevel' => CONTEXT_USER));
        // Update all the blog post tags.
        $sql = "UPDATE {tag_instance}\n                   SET component = 'core',\n                       contextid = (SELECT ctx.id\n                                      FROM {context} ctx\n                                      JOIN {post} p\n                                        ON p.userid = ctx.instanceid\n                                     WHERE ctx.contextlevel = :contextlevel\n                                       AND p.id = {tag_instance}.itemid)\n                 WHERE itemtype = 'post' AND contextid IS NULL";
        $DB->execute($sql, array('contextlevel' => CONTEXT_USER));
        // Update all the wiki page tags.
        $sql = "UPDATE {tag_instance}\n                   SET component = 'mod_wiki',\n                       contextid = (SELECT ctx.id\n                                      FROM {context} ctx\n                                      JOIN {course_modules} cm\n                                        ON cm.id = ctx.instanceid\n                                      JOIN {modules} m\n                                        ON m.id = cm.module\n                                      JOIN {wiki} w\n                                        ON w.id = cm.instance\n                                      JOIN {wiki_subwikis} sw\n                                        ON sw.wikiid = w.id\n                                      JOIN {wiki_pages} wp\n                                        ON wp.subwikiid = sw.id\n                                     WHERE m.name = 'wiki'\n                                       AND ctx.contextlevel = :contextlevel\n                                       AND wp.id = {tag_instance}.itemid)\n                 WHERE itemtype = 'wiki_pages' AND contextid IS NULL";
        $DB->execute($sql, array('contextlevel' => CONTEXT_MODULE));
        // Update all the question tags.
        $sql = "UPDATE {tag_instance}\n                   SET component = 'core_question',\n                       contextid = (SELECT qc.contextid\n                                      FROM {question} q\n                                      JOIN {question_categories} qc\n                                        ON q.category = qc.id\n                                     WHERE q.id = {tag_instance}.itemid)\n                 WHERE itemtype = 'question' AND contextid IS NULL";
        $DB->execute($sql);
        // Update all the tag tags.
        $sql = "UPDATE {tag_instance}\n                   SET component = 'core',\n                       contextid = :systemcontext\n                 WHERE itemtype = 'tag' AND contextid IS NULL";
        $DB->execute($sql, array('systemcontext' => context_system::instance()->id));
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2014032600.02);
    }
    if ($oldversion < 2014032700.01) {
        // Define field disabled to be added to task_scheduled.
        $table = new xmldb_table('task_scheduled');
        $field = new xmldb_field('disabled', XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, '0', 'customised');
        // Conditionally launch add field disabled.
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2014032700.01);
    }
    if ($oldversion < 2014032700.02) {
        // Update displayloginfailures setting.
        if (empty($CFG->displayloginfailures)) {
            set_config('displayloginfailures', 0);
        } else {
            set_config('displayloginfailures', 1);
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2014032700.02);
    }
    if ($oldversion < 2014040800.0) {
        // Define field availability to be added to course_modules.
        $table = new xmldb_table('course_modules');
        $field = new xmldb_field('availability', XMLDB_TYPE_TEXT, null, null, null, null, null, 'showdescription');
        // Conditionally launch add field availability.
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        // Define field availability to be added to course_sections.
        $table = new xmldb_table('course_sections');
        $field = new xmldb_field('availability', XMLDB_TYPE_TEXT, null, null, null, null, null, 'groupingid');
        // Conditionally launch add field availability.
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        // Update existing conditions to new format. This could be a slow
        // process, so begin by counting the number of affected modules/sections.
        // (Performance: On the OU system, these took ~0.3 seconds, with about
        // 20,000 results out of about 400,000 total rows in those tables.)
        $cmcount = $DB->count_records_sql("\n                SELECT COUNT(1)\n                  FROM {course_modules} cm\n                 WHERE cm.availablefrom != 0 OR\n                       cm.availableuntil != 0 OR\n                       EXISTS (SELECT 1 FROM {course_modules_availability} WHERE coursemoduleid = cm.id) OR\n                       EXISTS (SELECT 1 FROM {course_modules_avail_fields} WHERE coursemoduleid = cm.id)");
        $sectcount = $DB->count_records_sql("\n                SELECT COUNT(1)\n                  FROM {course_sections} cs\n                 WHERE cs.groupingid != 0 OR\n                       cs.availablefrom != 0 OR\n                       cs.availableuntil != 0 OR\n                       EXISTS (SELECT 1 FROM {course_sections_availability} WHERE coursesectionid = cs.id) OR\n                       EXISTS (SELECT 1 FROM {course_sections_avail_fields} WHERE coursesectionid = cs.id)");
        if ($cmcount + $sectcount > 0) {
            // Show progress bar and start db transaction.
            $transaction = $DB->start_delegated_transaction();
            $pbar = new progress_bar('availupdate', 500, true);
            // Loop through all course-modules.
            // (Performance: On the OU system, the query took <1 second for ~20k
            // results; updating all those entries took ~3 minutes.)
            $done = 0;
            $lastupdate = 0;
            $rs = $DB->get_recordset_sql("\n                    SELECT cm.id, cm.availablefrom, cm.availableuntil, cm.showavailability,\n                           COUNT(DISTINCT cma.id) AS availcount,\n                           COUNT(DISTINCT cmf.id) AS fieldcount\n                      FROM {course_modules} cm\n                           LEFT JOIN {course_modules_availability} cma ON cma.coursemoduleid = cm.id\n                           LEFT JOIN {course_modules_avail_fields} cmf ON cmf.coursemoduleid = cm.id\n                     WHERE cm.availablefrom != 0 OR\n                           cm.availableuntil != 0 OR\n                           cma.id IS NOT NULL OR\n                           cmf.id IS NOT NULL\n                  GROUP BY cm.id, cm.availablefrom, cm.availableuntil, cm.showavailability");
            foreach ($rs as $rec) {
                // Update progress initially and then once per second.
                if (time() != $lastupdate) {
                    $lastupdate = time();
                    $pbar->update($done, $cmcount + $sectcount, "Updating activity availability settings ({$done}/{$cmcount})");
                }
                // Get supporting records - only if there are any (to reduce the
                // number of queries where just date/group is used).
                if ($rec->availcount) {
                    $availrecs = $DB->get_records('course_modules_availability', array('coursemoduleid' => $rec->id));
                } else {
                    $availrecs = array();
                }
                if ($rec->fieldcount) {
                    $fieldrecs = $DB->get_records_sql("\n                            SELECT cmaf.userfield, cmaf.operator, cmaf.value, uif.shortname\n                              FROM {course_modules_avail_fields} cmaf\n                         LEFT JOIN {user_info_field} uif ON uif.id = cmaf.customfieldid\n                             WHERE cmaf.coursemoduleid = ?", array($rec->id));
                } else {
                    $fieldrecs = array();
                }
                // Update item.
                $availability = upgrade_availability_item(0, 0, $rec->availablefrom, $rec->availableuntil, $rec->showavailability, $availrecs, $fieldrecs);
                if ($availability) {
                    $DB->set_field('course_modules', 'availability', $availability, array('id' => $rec->id));
                }
                // Update progress.
                $done++;
            }
            $rs->close();
            // Loop through all course-sections.
            // (Performance: On the OU system, this took <1 second for, er, 150 results.)
            $done = 0;
            $rs = $DB->get_recordset_sql("\n                    SELECT cs.id, cs.groupingid, cs.availablefrom,\n                           cs.availableuntil, cs.showavailability,\n                           COUNT(DISTINCT csa.id) AS availcount,\n                           COUNT(DISTINCT csf.id) AS fieldcount\n                      FROM {course_sections} cs\n                           LEFT JOIN {course_sections_availability} csa ON csa.coursesectionid = cs.id\n                           LEFT JOIN {course_sections_avail_fields} csf ON csf.coursesectionid = cs.id\n                     WHERE cs.groupingid != 0 OR\n                           cs.availablefrom != 0 OR\n                           cs.availableuntil != 0 OR\n                           csa.id IS NOT NULL OR\n                           csf.id IS NOT NULL\n                  GROUP BY cs.id, cs.groupingid, cs.availablefrom,\n                           cs.availableuntil, cs.showavailability");
            foreach ($rs as $rec) {
                // Update progress once per second.
                if (time() != $lastupdate) {
                    $lastupdate = time();
                    $pbar->update($done + $cmcount, $cmcount + $sectcount, "Updating section availability settings ({$done}/{$sectcount})");
                }
                // Get supporting records - only if there are any (to reduce the
                // number of queries where just date/group is used).
                if ($rec->availcount) {
                    $availrecs = $DB->get_records('course_sections_availability', array('coursesectionid' => $rec->id));
                } else {
                    $availrecs = array();
                }
                if ($rec->fieldcount) {
                    $fieldrecs = $DB->get_records_sql("\n                            SELECT csaf.userfield, csaf.operator, csaf.value, uif.shortname\n                              FROM {course_sections_avail_fields} csaf\n                         LEFT JOIN {user_info_field} uif ON uif.id = csaf.customfieldid\n                             WHERE csaf.coursesectionid = ?", array($rec->id));
                } else {
                    $fieldrecs = array();
                }
                // Update item.
                $availability = upgrade_availability_item($rec->groupingid ? 1 : 0, $rec->groupingid, $rec->availablefrom, $rec->availableuntil, $rec->showavailability, $availrecs, $fieldrecs);
                if ($availability) {
                    $DB->set_field('course_sections', 'availability', $availability, array('id' => $rec->id));
                }
                // Update progress.
                $done++;
            }
            $rs->close();
            // Final progress update for 100%.
            $pbar->update($done + $cmcount, $cmcount + $sectcount, 'Availability settings updated for ' . ($cmcount + $sectcount) . ' activities and sections');
            $transaction->allow_commit();
        }
        // Drop tables which are not necessary because they are covered by the
        // new availability fields.
        $table = new xmldb_table('course_modules_availability');
        if ($dbman->table_exists($table)) {
            $dbman->drop_table($table);
        }
        $table = new xmldb_table('course_modules_avail_fields');
        if ($dbman->table_exists($table)) {
            $dbman->drop_table($table);
        }
        $table = new xmldb_table('course_sections_availability');
        if ($dbman->table_exists($table)) {
            $dbman->drop_table($table);
        }
        $table = new xmldb_table('course_sections_avail_fields');
        if ($dbman->table_exists($table)) {
            $dbman->drop_table($table);
        }
        // Drop unnnecessary fields from course_modules.
        $table = new xmldb_table('course_modules');
        $field = new xmldb_field('availablefrom');
        if ($dbman->field_exists($table, $field)) {
            $dbman->drop_field($table, $field);
        }
        $field = new xmldb_field('availableuntil');
        if ($dbman->field_exists($table, $field)) {
            $dbman->drop_field($table, $field);
        }
        $field = new xmldb_field('showavailability');
        if ($dbman->field_exists($table, $field)) {
            $dbman->drop_field($table, $field);
        }
        // Drop unnnecessary fields from course_sections.
        $table = new xmldb_table('course_sections');
        $field = new xmldb_field('availablefrom');
        if ($dbman->field_exists($table, $field)) {
            $dbman->drop_field($table, $field);
        }
        $field = new xmldb_field('availableuntil');
        if ($dbman->field_exists($table, $field)) {
            $dbman->drop_field($table, $field);
        }
        $field = new xmldb_field('showavailability');
        if ($dbman->field_exists($table, $field)) {
            $dbman->drop_field($table, $field);
        }
        $field = new xmldb_field('groupingid');
        if ($dbman->field_exists($table, $field)) {
            $dbman->drop_field($table, $field);
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2014040800.0);
    }
    if ($oldversion < 2014041500.01) {
        $table = new xmldb_table('user_info_data');
        $sql = 'SELECT DISTINCT info.id
                  FROM {user_info_data} info
            INNER JOIN {user_info_data} older
                    ON info.fieldid = older.fieldid
                   AND info.userid = older.userid
                   AND older.id < info.id';
        $transaction = $DB->start_delegated_transaction();
        $rs = $DB->get_recordset_sql($sql);
        foreach ($rs as $rec) {
            $DB->delete_records('user_info_data', array('id' => $rec->id));
        }
        $transaction->allow_commit();
        $oldindex = new xmldb_index('userid_fieldid', XMLDB_INDEX_NOTUNIQUE, array('userid', 'fieldid'));
        if ($dbman->index_exists($table, $oldindex)) {
            $dbman->drop_index($table, $oldindex);
        }
        $newindex = new xmldb_index('userid_fieldid', XMLDB_INDEX_UNIQUE, array('userid', 'fieldid'));
        if (!$dbman->index_exists($table, $newindex)) {
            $dbman->add_index($table, $newindex);
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2014041500.01);
    }
    if ($oldversion < 2014050100.0) {
        // Fixing possible wrong MIME type for DigiDoc files.
        $extensions = array('%.bdoc', '%.cdoc', '%.ddoc');
        $select = $DB->sql_like('filename', '?', false);
        foreach ($extensions as $extension) {
            $DB->set_field_select('files', 'mimetype', 'application/x-digidoc', $select, array($extension));
        }
        upgrade_main_savepoint(true, 2014050100.0);
    }
    // Moodle v2.7.0 release upgrade line.
    // Put any upgrade step following this.
    // MDL-32543 Make sure that the log table has correct length for action and url fields.
    if ($oldversion < 2014051200.02) {
        $table = new xmldb_table('log');
        $columns = $DB->get_columns('log');
        if ($columns['action']->max_length < 40) {
            $index1 = new xmldb_index('course-module-action', XMLDB_INDEX_NOTUNIQUE, array('course', 'module', 'action'));
            if ($dbman->index_exists($table, $index1)) {
                $dbman->drop_index($table, $index1);
            }
            $index2 = new xmldb_index('action', XMLDB_INDEX_NOTUNIQUE, array('action'));
            if ($dbman->index_exists($table, $index2)) {
                $dbman->drop_index($table, $index2);
            }
            $field = new xmldb_field('action', XMLDB_TYPE_CHAR, '40', null, XMLDB_NOTNULL, null, null, 'cmid');
            $dbman->change_field_precision($table, $field);
            $dbman->add_index($table, $index1);
            $dbman->add_index($table, $index2);
        }
        if ($columns['url']->max_length < 100) {
            $field = new xmldb_field('url', XMLDB_TYPE_CHAR, '100', null, XMLDB_NOTNULL, null, null, 'action');
            $dbman->change_field_precision($table, $field);
        }
        upgrade_main_savepoint(true, 2014051200.02);
    }
    if ($oldversion < 2014060300.0) {
        $gspath = get_config('assignfeedback_editpdf', 'gspath');
        if ($gspath !== false) {
            set_config('pathtogs', $gspath);
            unset_config('gspath', 'assignfeedback_editpdf');
        }
        upgrade_main_savepoint(true, 2014060300.0);
    }
    if ($oldversion < 2014061000.0) {
        // Fixing possible wrong MIME type for Publisher files.
        $filetypes = array('%.pub' => 'application/x-mspublisher');
        upgrade_mimetypes($filetypes);
        upgrade_main_savepoint(true, 2014061000.0);
    }
    if ($oldversion < 2014062600.01) {
        // We only want to delete DragMath if the directory no longer exists. If the directory
        // is present then it means it has been restored, so do not perform the uninstall.
        if (!check_dir_exists($CFG->libdir . '/editor/tinymce/plugins/dragmath', false)) {
            // Purge DragMath plugin which is incompatible with GNU GPL license.
            unset_all_config_for_plugin('tinymce_dragmath');
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2014062600.01);
    }
    // Switch the order of the fields in the files_reference index, to improve the performance of search_references.
    if ($oldversion < 2014070100.0) {
        $table = new xmldb_table('files_reference');
        $index = new xmldb_index('uq_external_file', XMLDB_INDEX_UNIQUE, array('repositoryid', 'referencehash'));
        if ($dbman->index_exists($table, $index)) {
            $dbman->drop_index($table, $index);
        }
        upgrade_main_savepoint(true, 2014070100.0);
    }
    if ($oldversion < 2014070101.0) {
        $table = new xmldb_table('files_reference');
        $index = new xmldb_index('uq_external_file', XMLDB_INDEX_UNIQUE, array('referencehash', 'repositoryid'));
        if (!$dbman->index_exists($table, $index)) {
            $dbman->add_index($table, $index);
        }
        upgrade_main_savepoint(true, 2014070101.0);
    }
    if ($oldversion < 2014072400.01) {
        $table = new xmldb_table('user_devices');
        $oldindex = new xmldb_index('pushid-platform', XMLDB_KEY_UNIQUE, array('pushid', 'platform'));
        if ($dbman->index_exists($table, $oldindex)) {
            $key = new xmldb_key('pushid-platform', XMLDB_KEY_UNIQUE, array('pushid', 'platform'));
            $dbman->drop_key($table, $key);
        }
        upgrade_main_savepoint(true, 2014072400.01);
    }
    if ($oldversion < 2014080801.0) {
        // Define index behaviour (not unique) to be added to question_attempts.
        $table = new xmldb_table('question_attempts');
        $index = new xmldb_index('behaviour', XMLDB_INDEX_NOTUNIQUE, array('behaviour'));
        // Conditionally launch add index behaviour.
        if (!$dbman->index_exists($table, $index)) {
            $dbman->add_index($table, $index);
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2014080801.0);
    }
    if ($oldversion < 2014082900.01) {
        // Fixing possible wrong MIME type for 7-zip and Rar files.
        $filetypes = array('%.7z' => 'application/x-7z-compressed', '%.rar' => 'application/x-rar-compressed');
        upgrade_mimetypes($filetypes);
        upgrade_main_savepoint(true, 2014082900.01);
    }
    if ($oldversion < 2014082900.02) {
        // Replace groupmembersonly usage with new availability system.
        $transaction = $DB->start_delegated_transaction();
        if ($CFG->enablegroupmembersonly) {
            // If it isn't already enabled, we need to enable availability.
            if (!$CFG->enableavailability) {
                set_config('enableavailability', 1);
            }
            // Count all course-modules with groupmembersonly set (for progress
            // bar).
            $total = $DB->count_records('course_modules', array('groupmembersonly' => 1));
            $pbar = new progress_bar('upgradegroupmembersonly', 500, true);
            // Get all these course-modules, one at a time.
            $rs = $DB->get_recordset('course_modules', array('groupmembersonly' => 1), 'course, id');
            $i = 0;
            foreach ($rs as $cm) {
                // Calculate and set new availability value.
                $availability = upgrade_group_members_only($cm->groupingid, $cm->availability);
                $DB->set_field('course_modules', 'availability', $availability, array('id' => $cm->id));
                // Update progress.
                $i++;
                $pbar->update($i, $total, "Upgrading groupmembersonly settings - {$i}/{$total}.");
            }
            $rs->close();
        }
        // Define field groupmembersonly to be dropped from course_modules.
        $table = new xmldb_table('course_modules');
        $field = new xmldb_field('groupmembersonly');
        // Conditionally launch drop field groupmembersonly.
        if ($dbman->field_exists($table, $field)) {
            $dbman->drop_field($table, $field);
        }
        // Unset old config variable.
        unset_config('enablegroupmembersonly');
        $transaction->allow_commit();
        upgrade_main_savepoint(true, 2014082900.02);
    }
    if ($oldversion < 2014100100.0) {
        // Define table messageinbound_handlers to be created.
        $table = new xmldb_table('messageinbound_handlers');
        // Adding fields to table messageinbound_handlers.
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
        $table->add_field('component', XMLDB_TYPE_CHAR, '100', null, XMLDB_NOTNULL, null, null);
        $table->add_field('classname', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null);
        $table->add_field('defaultexpiration', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '86400');
        $table->add_field('validateaddress', XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, '1');
        $table->add_field('enabled', XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, '0');
        // Adding keys to table messageinbound_handlers.
        $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->add_key('classname', XMLDB_KEY_UNIQUE, array('classname'));
        // Conditionally launch create table for messageinbound_handlers.
        if (!$dbman->table_exists($table)) {
            $dbman->create_table($table);
        }
        // Define table messageinbound_datakeys to be created.
        $table = new xmldb_table('messageinbound_datakeys');
        // Adding fields to table messageinbound_datakeys.
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
        $table->add_field('handler', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null);
        $table->add_field('datavalue', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null);
        $table->add_field('datakey', XMLDB_TYPE_CHAR, '64', null, null, null, null);
        $table->add_field('timecreated', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null);
        $table->add_field('expires', XMLDB_TYPE_INTEGER, '10', null, null, null, null);
        // Adding keys to table messageinbound_datakeys.
        $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->add_key('handler_datavalue', XMLDB_KEY_UNIQUE, array('handler', 'datavalue'));
        $table->add_key('handler', XMLDB_KEY_FOREIGN, array('handler'), 'messageinbound_handlers', array('id'));
        // Conditionally launch create table for messageinbound_datakeys.
        if (!$dbman->table_exists($table)) {
            $dbman->create_table($table);
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2014100100.0);
    }
    if ($oldversion < 2014100600.01) {
        // Define field aggregationstatus to be added to grade_grades.
        $table = new xmldb_table('grade_grades');
        $field = new xmldb_field('aggregationstatus', XMLDB_TYPE_CHAR, '10', null, XMLDB_NOTNULL, null, 'unknown', 'timemodified');
        // Conditionally launch add field aggregationstatus.
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        $field = new xmldb_field('aggregationweight', XMLDB_TYPE_NUMBER, '10, 5', null, null, null, null, 'aggregationstatus');
        // Conditionally launch add field aggregationweight.
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        // Define field aggregationcoef2 to be added to grade_items.
        $table = new xmldb_table('grade_items');
        $field = new xmldb_field('aggregationcoef2', XMLDB_TYPE_NUMBER, '10, 5', null, XMLDB_NOTNULL, null, '0', 'aggregationcoef');
        // Conditionally launch add field aggregationcoef2.
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        $field = new xmldb_field('weightoverride', XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, '0', 'needsupdate');
        // Conditionally launch add field weightoverride.
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2014100600.01);
    }
    if ($oldversion < 2014100600.02) {
        // Define field aggregationcoef2 to be added to grade_items_history.
        $table = new xmldb_table('grade_items_history');
        $field = new xmldb_field('aggregationcoef2', XMLDB_TYPE_NUMBER, '10, 5', null, XMLDB_NOTNULL, null, '0', 'aggregationcoef');
        // Conditionally launch add field aggregationcoef2.
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2014100600.02);
    }
    if ($oldversion < 2014100600.03) {
        // Define field weightoverride to be added to grade_items_history.
        $table = new xmldb_table('grade_items_history');
        $field = new xmldb_field('weightoverride', XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, '0', 'decimals');
        // Conditionally launch add field weightoverride.
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2014100600.03);
    }
    if ($oldversion < 2014100600.04) {
        // Set flags so we can display a notice on all courses that might
        // be affected by the uprade to natural aggregation.
        if (!get_config('grades_sumofgrades_upgrade_flagged', 'core')) {
            // 13 == SUM_OF_GRADES.
            $sql = 'SELECT DISTINCT courseid
                      FROM {grade_categories}
                     WHERE aggregation = ?';
            $courses = $DB->get_records_sql($sql, array(13));
            foreach ($courses as $course) {
                set_config('show_sumofgrades_upgrade_' . $course->courseid, 1);
                // Set each of the grade items to needing an update so that when the user visits the grade reports the
                // figures will be updated.
                $DB->set_field('grade_items', 'needsupdate', 1, array('courseid' => $course->courseid));
            }
            set_config('grades_sumofgrades_upgrade_flagged', 1);
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2014100600.04);
    }
    if ($oldversion < 2014100700.0) {
        // Define table messageinbound_messagelist to be created.
        $table = new xmldb_table('messageinbound_messagelist');
        // Adding fields to table messageinbound_messagelist.
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
        $table->add_field('messageid', XMLDB_TYPE_TEXT, null, null, XMLDB_NOTNULL, null, null);
        $table->add_field('userid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null);
        $table->add_field('address', XMLDB_TYPE_TEXT, null, null, XMLDB_NOTNULL, null, null);
        $table->add_field('timecreated', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null);
        // Adding keys to table messageinbound_messagelist.
        $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->add_key('userid', XMLDB_KEY_FOREIGN, array('userid'), 'user', array('id'));
        // Conditionally launch create table for messageinbound_messagelist.
        if (!$dbman->table_exists($table)) {
            $dbman->create_table($table);
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2014100700.0);
    }
    if ($oldversion < 2014100700.01) {
        // Define field visible to be added to cohort.
        $table = new xmldb_table('cohort');
        $field = new xmldb_field('visible', XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, '1', 'descriptionformat');
        // Conditionally launch add field visible.
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2014100700.01);
    }
    if ($oldversion < 2014100800.0) {
        // Remove qformat_learnwise (unless it has manually been added back).
        if (!file_exists($CFG->dirroot . '/question/format/learnwise/format.php')) {
            unset_all_config_for_plugin('qformat_learnwise');
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2014100800.0);
    }
    if ($oldversion < 2014101001.0) {
        // Some blocks added themselves to the my/ home page, but they did not declare the
        // subpage of the default my home page. While the upgrade script has been fixed, this
        // upgrade script will fix the data that was wrongly added.
        // We only proceed if we can find the right entry from my_pages. Private => 1 refers to
        // the constant value MY_PAGE_PRIVATE.
        if ($systempage = $DB->get_record('my_pages', array('userid' => null, 'private' => 1))) {
            // Select the blocks there could have been automatically added. showinsubcontexts is hardcoded to 0
            // because it is possible for administrators to have forced it on the my/ page by adding it to the
            // system directly rather than updating the default my/ page.
            $blocks = array('course_overview', 'private_files', 'online_users', 'badges', 'calendar_month', 'calendar_upcoming');
            list($blocksql, $blockparams) = $DB->get_in_or_equal($blocks, SQL_PARAMS_NAMED);
            $select = "parentcontextid = :contextid\n                    AND pagetypepattern = :page\n                    AND showinsubcontexts = 0\n                    AND subpagepattern IS NULL\n                    AND blockname {$blocksql}";
            $params = array('contextid' => context_system::instance()->id, 'page' => 'my-index');
            $params = array_merge($params, $blockparams);
            $DB->set_field_select('block_instances', 'subpagepattern', $systempage->id, $select, $params);
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2014101001.0);
    }
    if ($oldversion < 2014102000.0) {
        // Define field aggregatesubcats to be dropped from grade_categories.
        $table = new xmldb_table('grade_categories');
        $field = new xmldb_field('aggregatesubcats');
        // Conditionally launch drop field aggregatesubcats.
        if ($dbman->field_exists($table, $field)) {
            $sql = 'SELECT DISTINCT courseid
                      FROM {grade_categories}
                     WHERE aggregatesubcats = ?';
            $courses = $DB->get_records_sql($sql, array(1));
            foreach ($courses as $course) {
                set_config('show_aggregatesubcats_upgrade_' . $course->courseid, 1);
                // Set each of the grade items to needing an update so that when the user visits the grade reports the
                // figures will be updated.
                $DB->set_field('grade_items', 'needsupdate', 1, array('courseid' => $course->courseid));
            }
            $dbman->drop_field($table, $field);
        }
        // Main savepoint reached.
        upgrade_main_savepoint(true, 2014102000.0);
    }
    return true;
}
Exemplo n.º 13
0
/**
 * Upgrade code for the essay question type.
 * @param int $oldversion the version we are upgrading from.
 */
function xmldb_qtype_essay_upgrade($oldversion) {
    global $CFG, $DB;

    $dbman = $DB->get_manager();

    // Moodle v2.2.0 release upgrade line
    // Put any upgrade step following this.

    if ($oldversion < 2011102701) {
        $sql = "
                  FROM {question} q
                  JOIN {question_answers} qa ON qa.question = q.id

                 WHERE q.qtype = 'essay'
                   AND " . $DB->sql_isnotempty('question_answers', 'feedback', false, true);
        // In Moodle <= 2.0 essay had both question.generalfeedback and question_answers.feedback
        // This was silly, and in Moodel >= 2.1 only question.generalfeedback. To avoid
        // dataloss, we concatenate question_answers.feedback onto the end of question.generalfeedback.
        $count = $DB->count_records_sql("
                SELECT COUNT(1) $sql");
        if ($count) {
            $progressbar = new progress_bar('essay23', 500, true);
            $done = 0;

            $toupdate = $DB->get_recordset_sql("
                    SELECT q.id,
                           q.generalfeedback,
                           q.generalfeedbackformat,
                           qa.feedback,
                           qa.feedbackformat
                    $sql");

            foreach ($toupdate as $data) {
                $progressbar->update($done, $count, "Updating essay feedback ($done/$count).");
                upgrade_set_timeout(60);
                if ($data->generalfeedbackformat == $data->feedbackformat) {
                    $DB->set_field('question', 'generalfeedback',
                            $data->generalfeedback . $data->feedback,
                            array('id' => $data->id));

                } else {
                    $newdata = new stdClass();
                    $newdata->id = $data->id;
                    $newdata->generalfeedback =
                            qtype_essay_convert_to_html($data->generalfeedback, $data->generalfeedbackformat) .
                            qtype_essay_convert_to_html($data->feedback,        $data->feedbackformat);
                    $newdata->generalfeedbackformat = FORMAT_HTML;
                    $DB->update_record('question', $newdata);
                }
            }

            $progressbar->update($count, $count, "Updating essay feedback complete!");
            $toupdate->close();
        }

        // Essay savepoint reached.
        upgrade_plugin_savepoint(true, 2011102701, 'qtype', 'essay');
    }

    if ($oldversion < 2011102702) {
        // Then we delete the old question_answers rows for essay questions.
        $DB->delete_records_select('question_answers',
                "question IN (SELECT id FROM {question} WHERE qtype = 'essay')");

        // Essay savepoint reached.
        upgrade_plugin_savepoint(true, 2011102702, 'qtype', 'essay');
    }

    // Moodle v2.3.0 release upgrade line
    // Put any upgrade step following this.

    // Moodle v2.4.0 release upgrade line
    // Put any upgrade step following this.

    if ($oldversion < 2013011800) {
        // Then we delete the old question_answers rows for essay questions.
        $DB->delete_records_select('qtype_essay_options', "NOT EXISTS (
                SELECT 1 FROM {question} WHERE qtype = 'essay' AND
                    {question}.id = {qtype_essay_options}.questionid)");

        // Essay savepoint reached.
        upgrade_plugin_savepoint(true, 2013011800, 'qtype', 'essay');
    }

    if ($oldversion < 2013021700) {
        // Create new fields responsetemplate and responsetemplateformat in qtyep_essay_options table.
        $table = new xmldb_table('qtype_essay_options');
        $field = new xmldb_field('responsetemplate', XMLDB_TYPE_TEXT, null, null,
                    null, null, null, 'graderinfoformat');
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }

        $field = new xmldb_field('responsetemplateformat', XMLDB_TYPE_INTEGER, '4',
                null, XMLDB_NOTNULL, null, '0', 'responsetemplate');
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }

        $DB->execute("UPDATE {qtype_essay_options} SET responsetemplate = '',
                responsetemplateformat = " . FORMAT_HTML . " WHERE responsetemplate IS NULL");

        // Essay savepoint reached.
        upgrade_plugin_savepoint(true, 2013021700, 'qtype', 'essay');
    }

    // Moodle v2.5.0 release upgrade line.
    // Put any upgrade step following this.


    return true;
}
Exemplo n.º 14
0
/**
 * Update all grades in gradebook.
 *
 * @global object
 */
function lesson_upgrade_grades()
{
    global $DB;
    $sql = "SELECT COUNT('x')\n              FROM {lesson} l, {course_modules} cm, {modules} m\n             WHERE m.name='lesson' AND m.id=cm.module AND cm.instance=l.id";
    $count = $DB->count_records_sql($sql);
    $sql = "SELECT l.*, cm.idnumber AS cmidnumber, l.course AS courseid\n              FROM {lesson} l, {course_modules} cm, {modules} m\n             WHERE m.name='lesson' AND m.id=cm.module AND cm.instance=l.id";
    $rs = $DB->get_recordset_sql($sql);
    if ($rs->valid()) {
        $pbar = new progress_bar('lessonupgradegrades', 500, true);
        $i = 0;
        foreach ($rs as $lesson) {
            $i++;
            upgrade_set_timeout(60 * 5);
            // set up timeout, may also abort execution
            lesson_update_grades($lesson, 0, false);
            $pbar->update($i, $count, "Updating Lesson grades ({$i}/{$count}).");
        }
    }
    $rs->close();
}
Exemplo n.º 15
0
    function regrade_all_needed($quiz, $groupstudents) {
        global $DB, $OUTPUT;
        if (!has_capability('mod/quiz:regrade', $this->context)) {
            echo $OUTPUT->notification(get_string('regradenotallowed', 'quiz'));
            return;
        }
        // Fetch all attempts that need regrading
        if ($groupstudents) {
            list($usql, $params) = $DB->get_in_or_equal($groupstudents);
            $where = "qa.userid $usql AND ";
        } else {
            $where = '';
            $params = array();
        }
        $where .= "qa.quiz = ? AND qa.preview = 0 AND qa.uniqueid = qqr.attemptid AND qqr.regraded = 0";
        $params[] = $quiz->id;
        if (!$attempts = $DB->get_records_sql('SELECT qa.*, qqr.questionid FROM {quiz_attempts} qa, {quiz_question_regrade} qqr WHERE '. $where, $params)) {
            echo $OUTPUT->heading(get_string('noattemptstoregrade', 'quiz_overview'));
            return true;
        }
        $this->clear_regrade_table($quiz, $groupstudents);
        // Fetch all questions
        $questions = question_load_questions(explode(',',quiz_questions_in_quiz($quiz->questions)), 'qqi.grade AS maxgrade, qqi.id AS instance',
            '{quiz_question_instances} qqi ON qqi.quiz = ' . $quiz->id . ' AND q.id = qqi.question');

        // Print heading
        echo $OUTPUT->heading(get_string('regradingquiz', 'quiz', format_string($quiz->name)));

        $apb = new progress_bar('aregradingbar', 500, true);

        // Loop through all questions and all attempts and regrade while printing progress info
        $attemptstodo = count($attempts);
        $attemptsdone = 0;
        @flush();@ob_flush();
        $attemptschanged = array();
        foreach ($attempts as $attempt) {
            $question = $questions[$attempt->questionid];
            $changed = regrade_question_in_attempt($question, $attempt, $quiz, true);
            if ($changed) {
                $attemptschanged[] = $attempt->uniqueid;
                $usersschanged[] = $attempt->userid;
            }
            if (!empty($apb)) {
                $attemptsdone++;
                $a = new stdClass();
                $a->done = $attemptsdone;
                $a->todo = $attemptstodo;
                $apb->update($attemptsdone, $attemptstodo, get_string('attemptprogress', 'quiz_overview', $a));
            }
        }
        $this->check_overall_grades($quiz, array(), $attemptschanged);
    }
Exemplo n.º 16
0
/**
 * xmldb_hotpot_upgrade
 *
 * @param xxx $oldversion
 * @return xxx
 */
function xmldb_hotpot_upgrade($oldversion)
{
    global $CFG, $DB;
    // this flag will be set to true if any upgrade needs to empty the HotPot cache
    $empty_cache = false;
    $dbman = $DB->get_manager();
    //===== 1.9.0 upgrade line ======//
    // update hotpot grades from sites earlier than Moodle 1.9, 27th March 2008
    $newversion = 2007101511;
    if ($oldversion < $newversion) {
        // ensure "hotpot_upgrade_grades" function is available
        require_once $CFG->dirroot . '/mod/hotpot/lib.php';
        hotpot_upgrade_grades();
        upgrade_mod_savepoint(true, "{$newversion}", 'hotpot');
    }
    $newversion = 2008011200;
    if ($oldversion < $newversion) {
        // remove unused config setting
        unset_config('hotpot_initialdisable');
        upgrade_mod_savepoint(true, "{$newversion}", 'hotpot');
    }
    $newversion = 2010080301;
    if ($oldversion < $newversion) {
        // remove unused config settings
        unset_config('hotpot_showtimes');
        unset_config('hotpot_excelencodings');
        // modify table: hotpot
        $table = new xmldb_table('hotpot');
        // expected structure of hotpot table when we start this upgrade:
        // (i.e. this is how things were at the end of Moodle 1.9)
        //   id, course, name, summary, timeopen, timeclose, location, reference,
        //   outputformat, navigation, studentfeedback, studentfeedbackurl,
        //   forceplugins, shownextquiz, review, grade, grademethod, attempts,
        //   password, subnet, clickreporting, timecreated, timemodified
        // convert, move and rename fields ($newname => $oldfield)
        $fields = array('outputformat' => new xmldb_field('outputformat', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL), 'timeopen' => new xmldb_field('timeopen', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'studentfeedbackurl'), 'timeclose' => new xmldb_field('timeclose', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'timeopen'), 'grademethod' => new xmldb_field('grademethod', XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'grade'), 'sourcefile' => new xmldb_field('reference', XMLDB_TYPE_CHAR, '255', null, null, null, null, 'name'), 'sourcelocation' => new xmldb_field('location', XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'sourcefile'), 'entrytext' => new xmldb_field('summary', XMLDB_TYPE_TEXT, 'small', null, null, null, null, 'sourcelocation'), 'reviewoptions' => new xmldb_field('review', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'), 'attemptlimit' => new xmldb_field('attempts', XMLDB_TYPE_INTEGER, '6', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'reviewoptions'), 'gradeweighting' => new xmldb_field('grade', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'attemptlimit'));
        foreach ($fields as $newname => $field) {
            if ($dbman->field_exists($table, $field)) {
                xmldb_hotpot_fix_previous_field($dbman, $table, $field);
                $dbman->change_field_type($table, $field);
                if ($field->getName() != $newname) {
                    $dbman->rename_field($table, $field, $newname);
                }
            }
        }
        // add fields
        $fields = array(new xmldb_field('sourcefile', XMLDB_TYPE_CHAR, '255', null, null, null, null, 'name'), new xmldb_field('sourcetype', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, 'sourcefile'), new xmldb_field('sourceitemid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'sourcetype'), new xmldb_field('sourcelocation', XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'sourceitemid'), new xmldb_field('configfile', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, 'sourcelocation'), new xmldb_field('configitemid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'configfile'), new xmldb_field('configlocation', XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'configitemid'), new xmldb_field('entrycm', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0', 'configlocation'), new xmldb_field('entrygrade', XMLDB_TYPE_INTEGER, '6', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '100', 'entrycm'), new xmldb_field('entrypage', XMLDB_TYPE_INTEGER, '2', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'entrygrade'), new xmldb_field('entrytext', XMLDB_TYPE_TEXT, 'small', null, null, null, null, 'entrypage'), new xmldb_field('entryformat', XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'entrytext'), new xmldb_field('entryoptions', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'entryformat'), new xmldb_field('exitpage', XMLDB_TYPE_INTEGER, '2', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'entryoptions'), new xmldb_field('exittext', XMLDB_TYPE_TEXT, 'small', null, null, null, null, 'exitpage'), new xmldb_field('exitformat', XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'exittext'), new xmldb_field('exitoptions', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'exitformat'), new xmldb_field('exitcm', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0', 'exitoptions'), new xmldb_field('title', XMLDB_TYPE_INTEGER, '6', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '3', 'navigation'), new xmldb_field('stopbutton', XMLDB_TYPE_INTEGER, '2', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'title'), new xmldb_field('stoptext', XMLDB_TYPE_CHAR, '255', null, null, null, null, 'stopbutton'), new xmldb_field('usefilters', XMLDB_TYPE_INTEGER, '2', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'stoptext'), new xmldb_field('useglossary', XMLDB_TYPE_INTEGER, '2', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'usefilters'), new xmldb_field('usemediafilter', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, 'useglossary'), new xmldb_field('timelimit', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0', 'timeclose'), new xmldb_field('delay1', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'timelimit'), new xmldb_field('delay2', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'delay1'), new xmldb_field('delay3', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '2', 'delay2'), new xmldb_field('discarddetails', XMLDB_TYPE_INTEGER, '2', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'clickreporting'));
        foreach ($fields as $field) {
            if (!$dbman->field_exists($table, $field)) {
                xmldb_hotpot_fix_previous_field($dbman, $table, $field);
                $dbman->add_field($table, $field);
            }
        }
        // remove field: forceplugins (replaced by "usemediafilter")
        $field = new xmldb_field('forceplugins', XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0');
        if ($dbman->field_exists($table, $field)) {
            $DB->execute('UPDATE {hotpot} SET ' . "usemediafilter='moodle'" . ' WHERE forceplugins=1');
            $dbman->drop_field($table, $field);
        }
        // remove field: shownextquiz (replaced by "exitcm")
        $field = new xmldb_field('shownextquiz', XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0');
        if ($dbman->field_exists($table, $field)) {
            // set exitcm to show next HotPot: -4 = hotpot::ACTIVITY_SECTION_HOTPOT
            $DB->execute('UPDATE {hotpot} SET exitcm=-4 WHERE shownextquiz=1');
            $dbman->drop_field($table, $field);
        }
        // append "id" to fields that are foreign keys in other hotpot tables
        $fields = array('hotpot_attempts' => array('hotpot'), 'hotpot_details' => array('attempt'), 'hotpot_questions' => array('hotpot'), 'hotpot_responses' => array('attempt', 'question'));
        foreach ($fields as $tablename => $fieldnames) {
            $table = new xmldb_table($tablename);
            foreach ($fieldnames as $fieldname) {
                $field = new xmldb_field($fieldname, XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0');
                if ($dbman->field_exists($table, $field)) {
                    // maybe we should remove all indexes and keys
                    // using this $fieldname before we rename the field
                    $dbman->rename_field($table, $field, $fieldname . 'id');
                }
            }
        }
        // create new table: hotpot_cache
        $table = new xmldb_table('hotpot_cache');
        if (!$dbman->table_exists($table)) {
            $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
            $table->add_field('hotpotid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0');
            $table->add_field('slasharguments', XMLDB_TYPE_CHAR, '1', null, XMLDB_NOTNULL);
            $table->add_field('hotpot_enableobfuscate', XMLDB_TYPE_CHAR, '1', null, XMLDB_NOTNULL);
            $table->add_field('hotpot_enableswf', XMLDB_TYPE_CHAR, '1', null, XMLDB_NOTNULL);
            $table->add_field('name', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL);
            $table->add_field('sourcefile', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL);
            $table->add_field('sourcetype', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL);
            $table->add_field('sourcelocation', XMLDB_TYPE_INTEGER, '2', XMLDB_UNSIGNED, XMLDB_NOTNULL);
            $table->add_field('sourcelastmodified', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL);
            $table->add_field('sourceetag', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL);
            $table->add_field('configfile', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL);
            $table->add_field('configlocation', XMLDB_TYPE_INTEGER, '2', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0');
            $table->add_field('configlastmodified', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL);
            $table->add_field('configetag', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL);
            $table->add_field('navigation', XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0');
            $table->add_field('title', XMLDB_TYPE_INTEGER, '6', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0');
            $table->add_field('stopbutton', XMLDB_TYPE_INTEGER, '2', XMLDB_UNSIGNED, null, null, '0');
            $table->add_field('stoptext', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL);
            $table->add_field('usefilters', XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, null, null, '0');
            $table->add_field('useglossary', XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, null, null, '0');
            $table->add_field('usemediafilter', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, '0');
            $table->add_field('studentfeedback', XMLDB_TYPE_INTEGER, '4', null, XMLDB_NOTNULL, null, '0');
            $table->add_field('studentfeedbackurl', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL);
            $table->add_field('timelimit', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
            $table->add_field('delay3', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '-1');
            $table->add_field('clickreporting', XMLDB_TYPE_INTEGER, '2', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0');
            $table->add_field('content', XMLDB_TYPE_TEXT, 'medium', null, XMLDB_NOTNULL);
            $table->add_field('timemodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL);
            $table->add_field('md5key', XMLDB_TYPE_CHAR, '32', null, XMLDB_NOTNULL);
            // Add keys to table hotpot_cache
            $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
            $table->add_key('hotpotid', XMLDB_KEY_FOREIGN, array('hotpotid'), 'hotpot', array('id'));
            // Add indexes to table hotpot_cache
            $table->add_index('hotpotid-md5key', XMLDB_INDEX_NOTUNIQUE, array('hotpotid', 'md5key'));
            $dbman->create_table($table);
        }
        // add new logging actions
        log_update_descriptions('mod/hotpot');
        // hotpot savepoint reached
        upgrade_mod_savepoint(true, "{$newversion}", 'hotpot');
    }
    $newversion = 2010080302;
    if ($oldversion < $newversion) {
        // navigation setting of "none" is now "0" (was "6")
        $DB->execute('UPDATE {hotpot} SET navigation=0 WHERE navigation=6');
        // navigation's "give up" button, is replaced by the "stopbutton" field
        $DB->execute('UPDATE {hotpot} SET stopbutton=0 WHERE navigation=5');
        $DB->execute('UPDATE {hotpot} SET navigation=0 WHERE navigation=5');
        upgrade_mod_savepoint(true, "{$newversion}", 'hotpot');
    }
    $newversion = 2010080303;
    if ($oldversion < $newversion) {
        // modify table: hotpot_attempts
        $table = new xmldb_table('hotpot_attempts');
        // add field: timemodified
        $field = new xmldb_field('timemodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0');
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
            $DB->execute('UPDATE {hotpot_attempts} SET timemodified = timefinish WHERE timemodified=0');
            $DB->execute('UPDATE {hotpot_attempts} SET timemodified = timestart  WHERE timemodified=0');
        }
        upgrade_mod_savepoint(true, "{$newversion}", 'hotpot');
    }
    $newversion = 2010080305;
    if ($oldversion < $newversion) {
        // modify table: hotpot
        $table = new xmldb_table('hotpot');
        // change fields
        //  - entrycm         (-> signed)
        //  - outputformat    (-> varchar)
        //  - timelimit       (-> signed)
        //  - delay3          (-> signed)
        //  - attemptlimit    (-> unsigned)
        //  - gradeweighting  (-> unsigned)
        //  - grademethod     (-> unsigned)
        $fields = array(new xmldb_field('entrycm', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'), new xmldb_field('outputformat', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL), new xmldb_field('timelimit', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'), new xmldb_field('delay3', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '2'), new xmldb_field('attemptlimit', XMLDB_TYPE_INTEGER, '6', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'), new xmldb_field('gradeweighting', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'), new xmldb_field('grademethod', XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'));
        foreach ($fields as $field) {
            if ($dbman->field_exists($table, $field)) {
                xmldb_hotpot_fix_previous_field($dbman, $table, $field);
                $dbman->change_field_type($table, $field);
            }
        }
        upgrade_mod_savepoint(true, "{$newversion}", 'hotpot');
    }
    $newversion = 2010080306;
    if ($oldversion < $newversion) {
        // modify table: hotpot
        $table = new xmldb_table('hotpot');
        // rename field: gradelimit -> gradeweighting
        $field = new xmldb_field('gradelimit', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0');
        if ($dbman->field_exists($table, $field)) {
            $dbman->rename_field($table, $field, 'gradeweighting');
        }
        upgrade_mod_savepoint(true, "{$newversion}", 'hotpot');
    }
    $newversion = 2010080308;
    if ($oldversion < $newversion) {
        // add display fields to hotpot
        // (these fields were missing from access.xml so won't be on new sites)
        $tables = array('hotpot' => array(new xmldb_field('title', XMLDB_TYPE_INTEGER, '6', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '3', 'navigation'), new xmldb_field('stopbutton', XMLDB_TYPE_INTEGER, '2', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'title'), new xmldb_field('stoptext', XMLDB_TYPE_CHAR, '255', null, null, null, null, 'stopbutton'), new xmldb_field('usefilters', XMLDB_TYPE_INTEGER, '2', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'stoptext'), new xmldb_field('useglossary', XMLDB_TYPE_INTEGER, '2', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'usefilters'), new xmldb_field('usemediafilter', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, 'useglossary')));
        foreach ($tables as $tablename => $fields) {
            $table = new xmldb_table($tablename);
            foreach ($fields as $field) {
                xmldb_hotpot_fix_previous_field($dbman, $table, $field);
                if ($dbman->field_exists($table, $field)) {
                    $dbman->change_field_type($table, $field);
                } else {
                    $dbman->add_field($table, $field);
                }
            }
        }
        $table = new xmldb_table('hotpot');
        $field = new xmldb_field('forceplugins', XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0');
        if ($dbman->field_exists($table, $field)) {
            $DB->execute('UPDATE {hotpot} SET ' . "usemediafilter='moodle'" . ' WHERE forceplugins=1');
            $dbman->drop_field($table, $field);
        }
        // force certain fields to be not null
        $tables = array('hotpot' => array(new xmldb_field('entrygrade', XMLDB_TYPE_INTEGER, '6', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '100')), 'hotpot_cache' => array(new xmldb_field('stopbutton', XMLDB_TYPE_INTEGER, '2', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'), new xmldb_field('usefilters', XMLDB_TYPE_INTEGER, '2', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'), new xmldb_field('useglossary', XMLDB_TYPE_INTEGER, '2', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'), new xmldb_field('studentfeedback', XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0')));
        foreach ($tables as $tablename => $fields) {
            $table = new xmldb_table($tablename);
            foreach ($fields as $field) {
                if ($dbman->field_exists($table, $field)) {
                    $dbman->change_field_type($table, $field);
                }
            }
        }
        upgrade_mod_savepoint(true, "{$newversion}", 'hotpot');
    }
    $newversion = 2010080309;
    if ($oldversion < $newversion) {
        // force certain text fields to be not null
        $tables = array('hotpot' => array(new xmldb_field('sourcefile', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL), new xmldb_field('entrytext', XMLDB_TYPE_TEXT, 'small', null, XMLDB_NOTNULL), new xmldb_field('exittext', XMLDB_TYPE_TEXT, 'small', null, XMLDB_NOTNULL), new xmldb_field('stoptext', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL)));
        foreach ($tables as $tablename => $fields) {
            $table = new xmldb_table($tablename);
            foreach ($fields as $field) {
                if ($dbman->field_exists($table, $field)) {
                    $fieldname = $field->getName();
                    $DB->set_field_select($tablename, $fieldname, '', "{$fieldname} IS NULL");
                    $dbman->change_field_type($table, $field);
                }
            }
        }
        upgrade_mod_savepoint(true, "{$newversion}", 'hotpot');
    }
    $newversion = 2010080311;
    if ($oldversion < $newversion) {
        require_once $CFG->dirroot . '/mod/hotpot/locallib.php';
        /////////////////////////////////////
        /// new file storage migrate code ///
        /////////////////////////////////////
        // set up sql strings to select HotPots with Moodle 1.x file paths (i.e. no leading slash)
        $strupdating = get_string('migratingfiles', 'hotpot');
        $select = 'h.*, cm.id AS cmid';
        $from = '{hotpot} h, {course_modules} cm, {modules} m';
        $where = 'm.name=? AND m.id=cm.module AND cm.instance=h.id AND h.sourcefile<>?' . ' AND ' . $DB->sql_like('h.sourcefile', '?', false, false, true);
        // NOT LIKE
        $params = array('hotpot', '', '/%', 0);
        $orderby = 'h.course, h.id';
        // get HotPot records that need to be updated
        if ($count = $DB->count_records_sql("SELECT COUNT('x') FROM {$from} WHERE {$where}", $params)) {
            $rs = $DB->get_recordset_sql("SELECT {$select} FROM {$from} WHERE {$where} ORDER BY {$orderby}", $params);
        } else {
            $rs = false;
        }
        if ($rs) {
            $i = 0;
            $bar = new progress_bar('hotpotmigratefiles', 500, true);
            // get file storage object
            $fs = get_file_storage();
            if (class_exists('context_course')) {
                $sitecontext = context_course::instance(SITEID);
            } else {
                $sitecontext = get_context_instance(CONTEXT_COURSE, SITEID);
            }
            $coursecontext = null;
            $modulecontext = null;
            foreach ($rs as $hotpot) {
                // apply for more script execution time (3 mins)
                upgrade_set_timeout();
                // get course context for this $hotpot
                if ($coursecontext === null || $coursecontext->instanceid != $hotpot->course) {
                    if (class_exists('context_course')) {
                        $coursecontext = context_course::instance($hotpot->course);
                    } else {
                        $coursecontext = get_context_instance(CONTEXT_COURSE, $hotpot->course);
                    }
                }
                // get module context for this $hotpot/$task
                if ($modulecontext === null || $modulecontext->instanceid != $hotpot->cmid) {
                    if (class_exists('context_module')) {
                        $modulecontext = context_module::instance($hotpot->cmid);
                    } else {
                        $modulecontext = get_context_instance(CONTEXT_MODULE, $hotpot->cmid);
                    }
                }
                // actually there shouldn't be any urls in HotPot activities,
                // but this code will also be used to convert QuizPort to TaskChain
                if (preg_match('/^https?:\\/\\//i', $hotpot->sourcefile)) {
                    $url = $hotpot->sourcefile;
                    $path = parse_url($url, PHP_URL_PATH);
                } else {
                    $url = '';
                    $path = $hotpot->sourcefile;
                }
                $path = clean_param($path, PARAM_PATH);
                // this information should be enough to access the file
                // if it has been migrated into Moodle 2.0 file system
                $old_filename = basename($path);
                $old_filepath = dirname($path);
                if ($old_filepath == '.' || $old_filepath == '') {
                    $old_filepath = '/';
                } else {
                    $old_filepath = '/' . ltrim($old_filepath, '/');
                    // require leading slash
                    $old_filepath = rtrim($old_filepath, '/') . '/';
                    // require trailing slash
                }
                // update $hotpot->sourcefile, if necessary
                if ($hotpot->sourcefile != $old_filepath . $old_filename) {
                    $hotpot->sourcefile = $old_filepath . $old_filename;
                    $DB->set_field('hotpot', 'sourcefile', $hotpot->sourcefile, array('id' => $hotpot->id));
                }
                // set $courseid and $contextid from $task->$location
                // of where we expect to find the $file
                //   0 : HOTPOT_LOCATION_COURSEFILES
                //   1 : HOTPOT_LOCATION_SITEFILES
                //   2 : HOTPOT_LOCATION_WWW (not used)
                if ($hotpot->sourcelocation) {
                    $courseid = SITEID;
                    $contextid = $sitecontext->id;
                } else {
                    $courseid = $hotpot->course;
                    $contextid = $coursecontext->id;
                }
                // we expect to need the $filehash to get a file that has been migrated
                $filehash = sha1('/' . $contextid . '/course/legacy/0' . $old_filepath . $old_filename);
                // we might also need the old file path, if the file has not been migrated
                $oldfilepath = $CFG->dataroot . '/' . $courseid . $old_filepath . $old_filename;
                // set parameters used to add file to filearea
                // (sortorder=1 siginifies the "mainfile" in this filearea)
                $file_record = array('contextid' => $modulecontext->id, 'component' => 'mod_hotpot', 'filearea' => 'sourcefile', 'sortorder' => 1, 'itemid' => 0, 'filepath' => $old_filepath, 'filename' => $old_filename);
                // initialize sourcefile settings
                $hotpot->sourcefile = $old_filepath . $old_filename;
                $hotpot->sourcetype = '';
                $hotpot->sourceitemid = 0;
                if ($file = $fs->get_file($modulecontext->id, 'mod_hotpot', 'sourcefile', 0, $old_filepath, $old_filename)) {
                    // file already exists for this context - shouldn't happen !!
                    // maybe an earlier upgrade failed for some reason ?
                    // anyway we must do this check, so that create_file_from_xxx() does not abort
                } else {
                    if ($url) {
                        // file is on an external url - unusual ?!
                        $file = false;
                        // $fs->create_file_from_url($file_record, $url);
                    } else {
                        if ($file = $fs->get_file_by_hash($filehash)) {
                            // $file has already been migrated to Moodle's file system
                            // this is the route we expect most people to come :-)
                            $file = $fs->create_file_from_storedfile($file_record, $file);
                        } else {
                            if (file_exists($oldfilepath)) {
                                // $file still exists on server's filesystem - unusual ?!
                                $file = $fs->create_file_from_pathname($file_record, $oldfilepath);
                            } else {
                                // file was not migrated and is not on server's filesystem
                                $file = false;
                            }
                        }
                    }
                }
                // if source file did not exist, notify user of the problem
                if (empty($file)) {
                    if ($url) {
                        $msg = "course_modules.id={$hotpot->cmid}, url={$url}";
                    } else {
                        $msg = "course_modules.id={$hotpot->cmid}, path={$path}";
                    }
                    $params = array('update' => $hotpot->cmid, 'onclick' => 'this.target="_blank"');
                    $msg = html_writer::link(new moodle_url('/course/modedit.php', $params), $msg);
                    $msg = get_string('sourcefilenotfound', 'hotpot', $msg);
                    echo html_writer::tag('div', $msg, array('class' => 'notifyproblem'));
                }
                // set $hotpot->sourcetype
                if ($pos = strrpos($hotpot->sourcefile, '.')) {
                    $filetype = substr($hotpot->sourcefile, $pos + 1);
                    switch ($filetype) {
                        case 'jcl':
                            $hotpot->sourcetype = 'hp_6_jcloze_xml';
                            break;
                        case 'jcw':
                            $hotpot->sourcetype = 'hp_6_jcross_xml';
                            break;
                        case 'jmt':
                            $hotpot->sourcetype = 'hp_6_jmatch_xml';
                            break;
                        case 'jmx':
                            $hotpot->sourcetype = 'hp_6_jmix_xml';
                            break;
                        case 'jqz':
                            $hotpot->sourcetype = 'hp_6_jquiz_xml';
                            break;
                        case 'rhb':
                            $hotpot->sourcetype = 'hp_6_rhubarb_xml';
                            break;
                        case 'sqt':
                            $hotpot->sourcetype = 'hp_6_sequitur_xml';
                            break;
                        case 'htm':
                        case 'html':
                        default:
                            if ($file) {
                                $pathnamehash = $fs->get_pathname_hash($modulecontext->id, 'mod_hotpot', 'sourcefile', 0, $old_filepath, $old_filename);
                                if ($contenthash = $DB->get_field('files', 'contenthash', array('pathnamehash' => $pathnamehash))) {
                                    $l1 = $contenthash[0] . $contenthash[1];
                                    $l2 = $contenthash[2] . $contenthash[3];
                                    if (file_exists("{$CFG->dataroot}/filedir/{$l1}/{$l2}/{$contenthash}")) {
                                        $hotpot->sourcetype = hotpot::get_sourcetype($file);
                                    } else {
                                        $msg = html_writer::link(new moodle_url('/course/modedit.php', array('update' => $hotpot->cmid)), "course_modules.id={$hotpot->cmid}, path={$path}");
                                        $msg .= html_writer::empty_tag('br');
                                        $msg .= "filedir path={$l1}/{$l2}/{$contenthash}";
                                        $msg = get_string('sourcefilenotfound', 'hotpot', $msg);
                                        echo html_writer::tag('div', $msg, array('class' => 'notifyproblem'));
                                    }
                                }
                            }
                    }
                }
                // JMatch has 2 output formats
                //     14 : v6  : drop down menus : hp_6_jmatch_xml_v6
                //     15 : v6+ : drag-and-drop   : hp_6_jmatch_xml_v6_plus
                // JMix has 2 output formats
                //     14 : v6  : links           : hp_6_jmix_xml_v6
                //     15 : v6+ : drag-and-drop   : hp_6_jmix_xml_v6_plus
                // since drag-and-drop is the "best" outputformat for both types of quiz,
                // we only need to worry about HotPots whose outputformat was 14 (="v6")
                // set $hotpot->outputformat
                if ($hotpot->outputformat == 14 && ($hotpot->sourcetype == 'hp_6_jmatch_xml' || $hotpot->sourcetype == 'hp_6_jmix_xml')) {
                    $hotpot->outputformat = $hotpot->sourcetype . '_v6';
                } else {
                    $hotpot->outputformat = '';
                    //  = "best" output format
                }
                $DB->update_record('hotpot', $hotpot);
                // update progress bar
                $i++;
                $bar->update($i, $count, $strupdating . ": ({$i}/{$count})");
            }
            $rs->close();
        }
        upgrade_mod_savepoint(true, "{$newversion}", 'hotpot');
    }
    $newversion = 2010080316;
    if ($oldversion < $newversion) {
        // because the HotPot activities were probably hidden until now
        // we need to reset the course caches (using "course/lib.php")
        require_once $CFG->dirroot . '/course/lib.php';
        $courseids = array();
        if ($hotpots = $DB->get_records('hotpot', null, '', 'id,course')) {
            foreach ($hotpots as $hotpot) {
                $courseids[$hotpot->course] = true;
            }
            $courseids = array_keys($courseids);
        }
        unset($hotpots, $hotpot);
        foreach ($courseids as $courseid) {
            rebuild_course_cache($courseid, true);
        }
        unset($courseids, $courseid);
        // reset theme cache to force inclusion of new hotpot css
        theme_reset_all_caches();
        upgrade_mod_savepoint(true, "{$newversion}", 'hotpot');
    }
    $newversion = 2010080325;
    if ($oldversion < $newversion) {
        $table = new xmldb_table('hotpot');
        $fieldnames = array('sourceitemid', 'configitemid');
        foreach ($fieldnames as $fieldname) {
            $field = new xmldb_field($fieldname);
            if ($dbman->field_exists($table, $field)) {
                $dbman->drop_field($table, $field);
            }
        }
        upgrade_mod_savepoint(true, "{$newversion}", 'hotpot');
    }
    $newversion = 2010080330;
    if ($oldversion < $newversion) {
        require_once $CFG->dirroot . '/mod/hotpot/lib.php';
        hotpot_refresh_events();
    }
    $newversion = 2010080333;
    if ($oldversion < $newversion) {
        update_capabilities('mod/hotpot');
        upgrade_mod_savepoint(true, "{$newversion}", 'hotpot');
    }
    $newversion = 2010080339;
    if ($oldversion < $newversion) {
        $table = new xmldb_table('hotpot');
        $field = new xmldb_field('exitgrade', XMLDB_TYPE_INTEGER, '6', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'exitcm');
        xmldb_hotpot_fix_previous_field($dbman, $table, $field);
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        upgrade_mod_savepoint(true, "{$newversion}", 'hotpot');
    }
    $newversion = 2010080340;
    if ($oldversion < $newversion) {
        // force all text fields to be long text, the default for Moodle 2.3 and later
        $tables = array('hotpot' => array(new xmldb_field('entrytext', XMLDB_TYPE_TEXT, 'long', null, XMLDB_NOTNULL), new xmldb_field('exittext', XMLDB_TYPE_TEXT, 'long', null, XMLDB_NOTNULL)), 'hotpot_cache' => array(new xmldb_field('content', XMLDB_TYPE_TEXT, 'long', null, XMLDB_NOTNULL)), 'hotpot_details' => array(new xmldb_field('details', XMLDB_TYPE_TEXT, 'long', null, XMLDB_NOTNULL)), 'hotpot_questions' => array(new xmldb_field('name', XMLDB_TYPE_TEXT, 'long', null, XMLDB_NOTNULL)), 'hotpot_strings' => array(new xmldb_field('string', XMLDB_TYPE_TEXT, 'long', null, XMLDB_NOTNULL)));
        foreach ($tables as $tablename => $fields) {
            $table = new xmldb_table($tablename);
            foreach ($fields as $field) {
                if ($dbman->field_exists($table, $field)) {
                    $fieldname = $field->getName();
                    $DB->set_field_select($tablename, $fieldname, '', "{$fieldname} IS NULL");
                    $dbman->change_field_type($table, $field);
                }
            }
        }
        upgrade_mod_savepoint(true, "{$newversion}", 'hotpot');
    }
    $newversion = 2010080342;
    if ($oldversion < $newversion) {
        // force all MySQL integer fields to be signed, the default for Moodle 2.3 and later
        if ($DB->get_dbfamily() == 'mysql') {
            $prefix = $DB->get_prefix();
            $tables = $DB->get_tables();
            foreach ($tables as $table) {
                if (substr($table, 0, 6) == 'hotpot') {
                    $rs = $DB->get_recordset_sql("SHOW COLUMNS FROM {$CFG->prefix}{$table} WHERE type LIKE '%unsigned%'");
                    foreach ($rs as $column) {
                        // copied from as "lib/db/upgradelib.php"
                        $type = preg_replace('/\\s*unsigned/i', 'signed', $column->type);
                        $notnull = $column->null === 'NO' ? 'NOT NULL' : 'NULL';
                        $default = is_null($column->default) || $column->default === '' ? '' : "DEFAULT '{$column->default}'";
                        $autoinc = stripos($column->extra, 'auto_increment') === false ? '' : 'AUTO_INCREMENT';
                        $sql = "ALTER TABLE `{$prefix}{$table}` MODIFY COLUMN `{$column->field}` {$type} {$notnull} {$default} {$autoinc}";
                        $DB->change_database_structure($sql);
                    }
                }
            }
        }
        upgrade_mod_savepoint(true, "{$newversion}", 'hotpot');
    }
    $newversion = 2010080353;
    if ($oldversion < $newversion) {
        // remove any unwanted "course_files" folders that may have been created
        // when restoring Moodle 1.9 HotPot activities to a Moodle 2.x site
        // select all HotPot activities which have a "course_files" folder
        // but whose "sourcefile" path does not require such a folder
        $select = 'f.*,' . 'h.id AS hotpotid,' . 'h.sourcefile AS sourcefile';
        $from = '{hotpot} h,' . '{course_modules} cm,' . '{context} c,' . '{files} f';
        $where = $DB->sql_like('h.sourcefile', '?', false, false, true) . ' AND h.id=cm.instance' . ' AND cm.id=c.instanceid' . ' AND c.id=f.contextid' . ' AND f.component=?' . ' AND f.filearea=?' . ' AND f.filepath=?' . ' AND f.filename=?';
        $params = array('/course_files/%', 'mod_hotpot', 'sourcefile', '/course_files/', '.');
        if ($filerecords = $DB->get_records_sql("SELECT {$select} FROM {$from} WHERE {$where}", $params)) {
            $fs = get_file_storage();
            foreach ($filerecords as $filerecord) {
                $file = $fs->get_file_instance($filerecord);
                xmldb_hotpot_move_file($file, '/');
            }
        }
        upgrade_mod_savepoint(true, "{$newversion}", 'hotpot');
    }
    $newversion = 2010080366;
    if ($oldversion < $newversion) {
        if ($hotpots = $DB->get_records_select('hotpot', $DB->sql_like('sourcefile', '?'), array('%http://localhost/19/99/%'))) {
            foreach ($hotpots as $hotpot) {
                $sourcefile = str_replace('http://localhost/19/99/', '', $hotpot->sourcefile);
                $DB->set_field('hotpot', 'sourcefile', $sourcefile, array('id' => $hotpot->id));
            }
        }
        upgrade_mod_savepoint(true, "{$newversion}", 'hotpot');
    }
    $newversion = 2010080370;
    if ($oldversion < $newversion) {
        require_once $CFG->dirroot . '/mod/hotpot/locallib.php';
        $reviewoptions = 0;
        list($times, $items) = hotpot::reviewoptions_times_items();
        foreach ($times as $timename => $timevalue) {
            foreach ($items as $itemname => $itemvalue) {
                $reviewoptions += $timevalue & $itemvalue;
            }
        }
        // $reviewoptions should now be set to 62415
        $DB->set_field('hotpot', 'reviewoptions', $reviewoptions);
        upgrade_mod_savepoint(true, "{$newversion}", 'hotpot');
    }
    $newversion = 2013111685;
    if ($oldversion < $newversion) {
        $tables = array('hotpot' => array(new xmldb_field('allowpaste', XMLDB_TYPE_INTEGER, '2', null, XMLDB_NOTNULL, null, '0', 'stoptext')), 'hotpot_cache' => array(new xmldb_field('hotpot_bodystyles', XMLDB_TYPE_CHAR, '8', null, XMLDB_NOTNULL, null, null, 'slasharguments'), new xmldb_field('sourcerepositoryid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0', 'sourcelocation'), new xmldb_field('configrepositoryid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0', 'configlocation'), new xmldb_field('allowpaste', XMLDB_TYPE_INTEGER, '2', null, XMLDB_NOTNULL, null, '0', 'stoptext')));
        foreach ($tables as $table => $fields) {
            $table = new xmldb_table($table);
            foreach ($fields as $field) {
                xmldb_hotpot_fix_previous_field($dbman, $table, $field);
                if ($dbman->field_exists($table, $field)) {
                    $dbman->change_field_type($table, $field);
                } else {
                    $dbman->add_field($table, $field);
                }
            }
        }
        upgrade_mod_savepoint(true, "{$newversion}", 'hotpot');
    }
    $newversion = 2014011694;
    if ($oldversion < $newversion) {
        require_once $CFG->dirroot . '/mod/hotpot/lib.php';
        hotpot_update_grades();
        upgrade_mod_savepoint(true, "{$newversion}", 'hotpot');
    }
    $newversion = 2014042111;
    if ($oldversion < $newversion) {
        $empty_cache = true;
        upgrade_mod_savepoint(true, "{$newversion}", 'hotpot');
    }
    if ($empty_cache) {
        $DB->delete_records('hotpot_cache');
    }
    return true;
}
Exemplo n.º 17
0
        }
        redirect($returnurl);
        break;
    case 'restore':
        if ($clist) {
            list($usql, $params) = $DB->get_in_or_equal($clist);
            $DB->set_field_select('cohort', 'component', '', 'id ' . $usql, $params);
        }
        redirect($returnurl);
        break;
    case 'delete':
        if ($clist) {
            set_time_limit(0);
            echo $OUTPUT->header();
            echo $OUTPUT->heading(get_string('auth_cohorttoolmcae', 'auth_mcae'));
            $progress = new progress_bar('delcohort');
            $progress->create();
            $delcount = count($clist);
            $delcurrent = 1;
            foreach ($clist as $cid) {
                $cohort = $DB->get_record('cohort', array('contextid' => $context->id, 'id' => $cid));
                cohort_delete_cohort($cohort);
                $progress->update($delcurrent, $delcount, "{$delcurrent} / {$delcount}");
                $delcurrent++;
            }
        }
        echo $OUTPUT->continue_button($returnurl);
        echo $OUTPUT->footer();
        die;
        break;
}
Exemplo n.º 18
0
    die;
}
$url = new moodle_url('/mod/emarking/publish.php', array('id' => $cm->id));
$PAGE->set_pagelayout('incourse');
$PAGE->set_popup_notification_allowed(false);
$PAGE->set_url($url);
$PAGE->set_context($context);
$PAGE->set_course($course);
$PAGE->set_cm($cm);
$PAGE->set_title(get_string('publishtitle', 'mod_emarking'));
$PAGE->set_heading($course->fullname);
$PAGE->navbar->add(get_string('publishtitle', 'mod_emarking'));
echo $OUTPUT->header();
echo $OUTPUT->heading(get_string('publishinggrades', 'mod_emarking'));
// Create progress bar
$pbar = new progress_bar('publish', 500, true);
emarking_calculate_grades_users($emarking);
// Count documents ignored and processed
$totaldocumentsprocessed = 0;
$totaldocumentsignored = 0;
$totalsubmissions = count($submissions);
foreach ($submissions as $submissionid) {
    if (!($submission = $DB->get_record('emarking_submission', array('id' => $submissionid)))) {
        $totaldocumentsignored++;
        continue;
    }
    if (!($student = $DB->get_record('user', array('id' => $submission->student)))) {
        $totaldocumentsignored++;
        continue;
    }
    if (emarking_multi_create_response_pdf($submission, $student, $context, $cmid)) {
Exemplo n.º 19
0
 /**
  * Renders a progress bar.
  *
  * Do not use $OUTPUT->render($bar), instead use progress_bar::create().
  *
  * @param  progress_bar $bar The bar.
  * @return string HTML fragment
  */
 public function render_progress_bar(progress_bar $bar)
 {
     global $PAGE;
     $data = $bar->export_for_template($this);
     return $this->render_from_template('core/progress_bar', $data);
 }
Exemplo n.º 20
0
function xmldb_scorm_upgrade($oldversion)
{
    global $CFG, $DB;
    $dbman = $DB->get_manager();
    $result = true;
    //===== 1.9.0 upgrade line ======//
    // Adding missing 'whatgrade' field to table scorm
    if ($result && $oldversion < 2008073000) {
        $table = new xmldb_table('scorm');
        $field = new xmldb_field('whatgrade');
        $field->set_attributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'grademethod');
        /// Launch add field whatgrade
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        upgrade_mod_savepoint($result, 2008073000, 'scorm');
    }
    if ($result && $oldversion < 2008082500) {
        /// Define field scormtype to be added to scorm
        $table = new xmldb_table('scorm');
        $field = new xmldb_field('scormtype', XMLDB_TYPE_CHAR, '50', null, XMLDB_NOTNULL, null, 'local', 'name');
        /// Launch add field scormtype
        $dbman->add_field($table, $field);
        /// scorm savepoint reached
        upgrade_mod_savepoint($result, 2008082500, 'scorm');
    }
    if ($result && $oldversion < 2008090300) {
        /// Define field sha1hash to be added to scorm
        $table = new xmldb_table('scorm');
        $field = new xmldb_field('sha1hash', XMLDB_TYPE_CHAR, '40', null, null, null, null, 'updatefreq');
        /// Launch add field sha1hash
        $dbman->add_field($table, $field);
        /// scorm savepoint reached
        upgrade_mod_savepoint($result, 2008090300, 'scorm');
    }
    if ($result && $oldversion < 2008090301) {
        /// Define field revision to be added to scorm
        $table = new xmldb_table('scorm');
        $field = new xmldb_field('revision', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'md5hash');
        /// Launch add field revision
        $dbman->add_field($table, $field);
        /// scorm savepoint reached
        upgrade_mod_savepoint($result, 2008090301, 'scorm');
    }
    if ($result && $oldversion < 2008090302) {
        $sql = "UPDATE {scorm}\n                   SET scormtype = 'external'\n                 WHERE reference LIKE ? OR reference LIKE ? OR reference LIKE ?";
        $DB->execute($sql, array('http://%imsmanifest.xml', 'https://%imsmanifest.xml', 'www.%imsmanifest.xml'));
        $sql = "UPDATE {scorm}\n                   SET scormtype = 'localsync'\n                 WHERE reference LIKE ? OR reference LIKE ? OR reference LIKE ?\n                       OR reference LIKE ? OR reference LIKE ? OR reference LIKE ?";
        $DB->execute($sql, array('http://%.zip', 'https://%.zip', 'www.%.zip', 'http://%.pif', 'https://%.pif', 'www.%.pif'));
        $sql = "UPDATE {scorm} SET scormtype = 'imsrepository' WHERE reference LIKE ?";
        $DB->execute($sql, array('#%'));
        /// scorm savepoint reached
        upgrade_mod_savepoint($result, 2008090302, 'scorm');
    }
    if ($result && $oldversion < 2008090303) {
        //remove obsoleted config settings
        unset_config('scorm_advancedsettings');
        unset_config('scorm_windowsettings');
        /// scorm savepoint reached
        upgrade_mod_savepoint($result, 2008090303, 'scorm');
    }
    if ($result && $oldversion < 2008090304) {
        /////////////////////////////////////
        /// new file storage upgrade code ///
        /////////////////////////////////////
        function scorm_migrate_content_files($context, $base, $path)
        {
            global $CFG, $OUTPUT;
            $fullpathname = $base . $path;
            $fs = get_file_storage();
            $filearea = 'scorm_content';
            $items = new DirectoryIterator($fullpathname);
            foreach ($items as $item) {
                if ($item->isDot()) {
                    unset($item);
                    // release file handle
                    continue;
                }
                if ($item->isLink()) {
                    // do not follow symlinks - they were never supported in moddata, sorry
                    unset($item);
                    // release file handle
                    continue;
                }
                if ($item->isFile()) {
                    if (!$item->isReadable()) {
                        echo $OUTPUT->notification(" File not readable, skipping: " . $fullpathname . $item->getFilename());
                        unset($item);
                        // release file handle
                        continue;
                    }
                    $filepath = clean_param($path, PARAM_PATH);
                    $filename = clean_param($item->getFilename(), PARAM_FILE);
                    $oldpathname = $fullpathname . $item->getFilename();
                    if ($filename === '') {
                        continue;
                        unset($item);
                        // release file handle
                    }
                    if (!$fs->file_exists($context->id, $filearea, '0', $filepath, $filename)) {
                        $file_record = array('contextid' => $context->id, 'filearea' => $filearea, 'itemid' => 0, 'filepath' => $filepath, 'filename' => $filename, 'timecreated' => $item->getCTime(), 'timemodified' => $item->getMTime());
                        unset($item);
                        // release file handle
                        if ($fs->create_file_from_pathname($file_record, $oldpathname)) {
                            @unlink($oldpathname);
                        }
                    } else {
                        unset($item);
                        // release file handle
                    }
                } else {
                    //migrate recursively all subdirectories
                    $oldpathname = $fullpathname . $item->getFilename() . '/';
                    $subpath = $path . $item->getFilename() . '/';
                    unset($item);
                    // release file handle
                    scorm_migrate_content_files($context, $base, $subpath);
                    @rmdir($oldpathname);
                    // deletes dir if empty
                }
            }
            unset($items);
            //release file handles
        }
        $fs = get_file_storage();
        $sqlfrom = "FROM {scorm} s\n                    JOIN {modules} m ON m.name = 'scorm'\n                    JOIN {course_modules} cm ON (cm.module = m.id AND cm.instance = s.id)";
        $count = $DB->count_records_sql("SELECT COUNT('x') {$sqlfrom}");
        if ($rs = $DB->get_recordset_sql("SELECT s.id, s.scormtype, s.reference, s.course, cm.id AS cmid {$sqlfrom} ORDER BY s.course, s.id")) {
            $pbar = new progress_bar('migratescormfiles', 500, true);
            $i = 0;
            foreach ($rs as $scorm) {
                $i++;
                upgrade_set_timeout(180);
                // set up timeout, may also abort execution
                $pbar->update($i, $count, "Migrating scorm files - {$i}/{$count}.");
                $context = get_context_instance(CONTEXT_MODULE, $scorm->cmid);
                $coursecontext = get_context_instance(CONTEXT_COURSE, $scorm->course);
                // first copy local packages if found - do not delete in case they are shared ;-)
                if ($scorm->scormtype === 'local' and preg_match('/.*(\\.zip|\\.pif)$/i', $scorm->reference)) {
                    $packagefile = '/' . clean_param($scorm->reference, PARAM_PATH);
                    $pathnamehash = sha1($coursecontext->id . 'course_content0' . $packagefile);
                    if ($file = $fs->get_file_by_hash($pathnamehash)) {
                        $file_record = array('scontextid' => $context->id, 'filearea' => 'scorm_pacakge', 'itemid' => 0, 'filepath' => '/');
                        $packagefile = $fs->create_file_from_storedfile($file_record, $file);
                        $scorm->reference = $packagefile->get_filename();
                    } else {
                        $scorm->reference = '';
                    }
                    $DB->update_record('scorm', $scorm);
                }
                // now migrate the extracted package
                $basepath = "{$CFG->dataroot}/{$scorm->course}/{$CFG->moddata}/scorm/{$scorm->id}";
                if (!is_dir($basepath)) {
                    //no files?
                    continue;
                }
                scorm_migrate_content_files($context, $basepath, '/');
                // remove dirs if empty
                @rmdir("{$CFG->dataroot}/{$scorm->course}/{$CFG->moddata}/scorm/{$scorm->id}/");
                @rmdir("{$CFG->dataroot}/{$scorm->course}/{$CFG->moddata}/scorm/");
                @rmdir("{$CFG->dataroot}/{$scorm->course}/{$CFG->moddata}/");
            }
            $rs->close();
        }
        /// scorm savepoint reached
        upgrade_mod_savepoint($result, 2008090304, 'scorm');
    }
    if ($result && $oldversion < 2008090305) {
        /// Define new fields forcecompleted, forcenewattempt, displayattemptstatus, and displaycoursestructure to be added to scorm
        $table = new xmldb_table('scorm');
        $field = new xmldb_field('forcecompleted', XMLDB_TYPE_INTEGER, '1', null, null, null, '0', 'maxattempt');
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        $field = new xmldb_field('forcenewattempt', XMLDB_TYPE_INTEGER, '1', null, null, null, '0', 'forcecompleted');
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        $field = new xmldb_field('lastattemptlock', XMLDB_TYPE_INTEGER, '1', null, null, null, '0', 'forcenewattempt');
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        $field = new xmldb_field('displayattemptstatus', XMLDB_TYPE_INTEGER, '1', null, null, null, '1', 'lastattemptlock');
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        $field = new xmldb_field('displaycoursestructure', XMLDB_TYPE_INTEGER, '1', null, null, null, '1', 'displayattemptstatus');
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        /// scorm savepoint reached
        upgrade_mod_savepoint($result, 2008090305, 'scorm');
    }
    // remove redundant config values
    if ($result && $oldversion < 2008090306) {
        /*
        * comment this out as it is handled by the update mark 2008090310 below
        * left for historical documentation as some early adopters may have done
        * this already.
        $redundant_config = array(
                        'scorm_allowapidebug',
                        'scorm_allowtypeexternal',
                        'scorm_allowtypeimsrepository',
                        'scorm_allowtypelocalsync',
                        'scorm_apidebugmask',
                        'scorm_frameheight',
                        'scorm_framewidth',
                        'scorm_maxattempts',
                        'scorm_updatetime');
                foreach ($redundant_config as $rcfg) {
           if (isset($CFG->$rcfg)) {
               unset_config($rcfg);
           }
                }
        */
        /// scorm savepoint reached
        upgrade_mod_savepoint($result, 2008090306, 'scorm');
    }
    // remove redundant config values
    if ($result && $oldversion < 2008090307) {
        /*
        * comment this out as it is handled by the update mark 2008090310 below
        * left for historical documentation as some early adopters may have done
        * this already.
        $redundant_config = array(
                        'scorm_allowapidebug',
                        'scorm_allowtypeexternal',
                        'scorm_allowtypeimsrepository',
                        'scorm_allowtypelocalsync',
                        'scorm_apidebugmask',
                        'scorm_frameheight',
                        'scorm_framewidth',
                        'scorm_maxattempts',
                        'scorm_updatetime',
                        'scorm_resizable',
                        'scorm_scrollbars',
                        'scorm_directories',
                        'scorm_location',
                        'scorm_menubar',
                        'scorm_toolbar',
                        'scorm_status',
                        'scorm_grademethod',
                        'scorm_maxgrade',
                        'scorm_whatgrade',
                        'scorm_popup',
                        'scorm_skipview',
                        'scorm_hidebrowse',
                        'scorm_hidetoc',
                        'scorm_hidenav',
                        'scorm_auto',
                        'scorm_updatefreq'
        );
                foreach ($redundant_config as $rcfg) {
           if (isset($CFG->$rcfg)) {
               unset_config($rcfg);
           }
                }
        */
        /// scorm savepoint reached
        upgrade_mod_savepoint($result, 2008090307, 'scorm');
    }
    if ($result && $oldversion < 2008090308) {
        $table = new xmldb_table('scorm');
        $field = new xmldb_field('timeopen', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'height');
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        $field = new xmldb_field('timeclose', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'timeopen');
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        /// scorm savepoint reached
        upgrade_mod_savepoint($result, 2008090308, 'scorm');
    }
    if ($result && $oldversion < 2008090310) {
        // take above blocks that delete config and move the values in to config_plugins
        $redundant_config = array('scorm_allowapidebug', 'scorm_allowtypeexternal', 'scorm_allowtypeimsrepository', 'scorm_allowtypelocalsync', 'scorm_apidebugmask', 'scorm_frameheight', 'scorm_framewidth', 'scorm_maxattempts', 'scorm_updatetime', 'scorm_resizable', 'scorm_scrollbars', 'scorm_directories', 'scorm_location', 'scorm_menubar', 'scorm_toolbar', 'scorm_status', 'scorm_grademethod', 'scorm_maxgrade', 'scorm_whatgrade', 'scorm_popup', 'scorm_skipview', 'scorm_hidebrowse', 'scorm_hidetoc', 'scorm_hidenav', 'scorm_auto', 'scorm_updatefreq', 'scorm_displayattemptstatus', 'scorm_displaycoursestructure', 'scorm_forcecompleted', 'scorm_forcenewattempt', 'scorm_lastattemptlock');
        foreach ($redundant_config as $rcfg) {
            if (isset($CFG->{$rcfg})) {
                $shortname = substr($rcfg, 6);
                $result = $result && set_config($shortname, $CFG->{$rcfg}, 'scorm');
                $result = $result && unset_config($rcfg);
            }
        }
        /// scorm savepoint reached
        upgrade_mod_savepoint($result, 2008090310, 'scorm');
    }
    if ($result && $oldversion < 2009042000) {
        /// Rename field summary on table scorm to intro
        $table = new xmldb_table('scorm');
        $field = new xmldb_field('summary', XMLDB_TYPE_TEXT, 'small', null, XMLDB_NOTNULL, null, null, 'reference');
        /// Launch rename field summary
        $dbman->rename_field($table, $field, 'intro');
        /// scorm savepoint reached
        upgrade_mod_savepoint($result, 2009042000, 'scorm');
    }
    if ($result && $oldversion < 2009042001) {
        /// Define field introformat to be added to scorm
        $table = new xmldb_table('scorm');
        $field = new xmldb_field('introformat', XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'intro');
        /// Launch add field introformat
        $dbman->add_field($table, $field);
        /// scorm savepoint reached
        upgrade_mod_savepoint($result, 2009042001, 'scorm');
    }
    return $result;
}
Exemplo n.º 21
0
/**
 * This file keeps track of upgrades to
 * the forum module
 *
 * Sometimes, changes between versions involve
 * alterations to database structures and other
 * major things that may break installations.
 *
 * The upgrade function in this file will attempt
 * to perform all the necessary actions to upgrade
 * your older installation to the current version.
 *
 * If there's something it cannot do itself, it
 * will tell you what you need to do.
 *
 * The commands in here will all be database-neutral,
 * using the methods of database_manager class
 *
 * Please do not forget to use upgrade_set_timeout()
 * before any action that may take longer time to finish.
 *
 * @package mod-forum
 * @copyright 2003 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com}
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
function xmldb_forum_upgrade($oldversion)
{
    global $CFG, $DB, $OUTPUT;
    $dbman = $DB->get_manager();
    // loads ddl manager and xmldb classes
    //===== 1.9.0 upgrade line ======//
    if ($oldversion < 2007101511) {
        //MDL-13866 - send forum ratins to gradebook again
        require_once $CFG->dirroot . '/mod/forum/lib.php';
        forum_upgrade_grades();
        upgrade_mod_savepoint(true, 2007101511, 'forum');
    }
    if ($oldversion < 2008072800) {
        /// Define field completiondiscussions to be added to forum
        $table = new xmldb_table('forum');
        $field = new xmldb_field('completiondiscussions');
        $field->set_attributes(XMLDB_TYPE_INTEGER, '9', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'blockperiod');
        /// Launch add field completiondiscussions
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        $field = new xmldb_field('completionreplies');
        $field->set_attributes(XMLDB_TYPE_INTEGER, '9', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'completiondiscussions');
        /// Launch add field completionreplies
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        /// Define field completionposts to be added to forum
        $field = new xmldb_field('completionposts');
        $field->set_attributes(XMLDB_TYPE_INTEGER, '9', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'completionreplies');
        /// Launch add field completionposts
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        upgrade_mod_savepoint(true, 2008072800, 'forum');
    }
    if ($oldversion < 2008081900) {
        /////////////////////////////////////
        /// new file storage upgrade code ///
        /////////////////////////////////////
        $fs = get_file_storage();
        $empty = $DB->sql_empty();
        // silly oracle empty string handling workaround
        $sqlfrom = "FROM {forum_posts} p\n                    JOIN {forum_discussions} d ON d.id = p.discussion\n                    JOIN {forum} f ON f.id = d.forum\n                    JOIN {modules} m ON m.name = 'forum'\n                    JOIN {course_modules} cm ON (cm.module = m.id AND cm.instance = f.id)\n                   WHERE p.attachment <> '{$empty}' AND p.attachment <> '1'";
        $count = $DB->count_records_sql("SELECT COUNT('x') {$sqlfrom}");
        $rs = $DB->get_recordset_sql("SELECT p.id, p.attachment, p.userid, d.forum, f.course, cm.id AS cmid {$sqlfrom} ORDER BY f.course, f.id, d.id");
        if ($rs->valid()) {
            $pbar = new progress_bar('migrateforumfiles', 500, true);
            $i = 0;
            foreach ($rs as $post) {
                $i++;
                upgrade_set_timeout(60);
                // set up timeout, may also abort execution
                $pbar->update($i, $count, "Migrating forum posts - {$i}/{$count}.");
                $filepath = "{$CFG->dataroot}/{$post->course}/{$CFG->moddata}/forum/{$post->forum}/{$post->id}/{$post->attachment}";
                if (!is_readable($filepath)) {
                    //file missing??
                    echo $OUTPUT->notification("File not readable, skipping: " . $filepath);
                    $post->attachment = '';
                    $DB->update_record('forum_posts', $post);
                    continue;
                }
                $context = get_context_instance(CONTEXT_MODULE, $post->cmid);
                $filearea = 'attachment';
                $filename = clean_param($post->attachment, PARAM_FILE);
                if ($filename === '') {
                    echo $OUTPUT->notification("Unsupported post filename, skipping: " . $filepath);
                    $post->attachment = '';
                    $DB->update_record('forum_posts', $post);
                    continue;
                }
                if (!$fs->file_exists($context->id, 'mod_forum', $filearea, $post->id, '/', $filename)) {
                    $file_record = array('contextid' => $context->id, 'component' => 'mod_forum', 'filearea' => $filearea, 'itemid' => $post->id, 'filepath' => '/', 'filename' => $filename, 'userid' => $post->userid);
                    if ($fs->create_file_from_pathname($file_record, $filepath)) {
                        $post->attachment = '1';
                        $DB->update_record('forum_posts', $post);
                        unlink($filepath);
                    }
                }
                // remove dirs if empty
                @rmdir("{$CFG->dataroot}/{$post->course}/{$CFG->moddata}/forum/{$post->forum}/{$post->id}");
                @rmdir("{$CFG->dataroot}/{$post->course}/{$CFG->moddata}/forum/{$post->forum}");
                @rmdir("{$CFG->dataroot}/{$post->course}/{$CFG->moddata}/forum");
            }
        }
        $rs->close();
        upgrade_mod_savepoint(true, 2008081900, 'forum');
    }
    if ($oldversion < 2008090800) {
        /// Define field maxattachments to be added to forum
        $table = new xmldb_table('forum');
        $field = new xmldb_field('maxattachments', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '1', 'maxbytes');
        /// Conditionally launch add field maxattachments
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        /// forum savepoint reached
        upgrade_mod_savepoint(true, 2008090800, 'forum');
    }
    if ($oldversion < 2009042000) {
        /// Rename field format on table forum_posts to messageformat
        $table = new xmldb_table('forum_posts');
        $field = new xmldb_field('format', XMLDB_TYPE_INTEGER, '2', null, XMLDB_NOTNULL, null, '0', 'message');
        /// Launch rename field format
        $dbman->rename_field($table, $field, 'messageformat');
        /// forum savepoint reached
        upgrade_mod_savepoint(true, 2009042000, 'forum');
    }
    if ($oldversion < 2009042001) {
        /// Define field messagetrust to be added to forum_posts
        $table = new xmldb_table('forum_posts');
        $field = new xmldb_field('messagetrust', XMLDB_TYPE_INTEGER, '2', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'messageformat');
        /// Launch add field messagetrust
        $dbman->add_field($table, $field);
        /// forum savepoint reached
        upgrade_mod_savepoint(true, 2009042001, 'forum');
    }
    if ($oldversion < 2009042002) {
        $trustmark = '#####TRUSTTEXT#####';
        $rs = $DB->get_recordset_sql("SELECT * FROM {forum_posts} WHERE message LIKE ?", array($trustmark . '%'));
        foreach ($rs as $post) {
            if (strpos($post->message, $trustmark) !== 0) {
                // probably lowercase in some DBs?
                continue;
            }
            $post->message = str_replace($trustmark, '', $post->message);
            $post->messagetrust = 1;
            $DB->update_record('forum_posts', $post);
        }
        $rs->close();
        /// forum savepoint reached
        upgrade_mod_savepoint(true, 2009042002, 'forum');
    }
    if ($oldversion < 2009042003) {
        /// Define field introformat to be added to forum
        $table = new xmldb_table('forum');
        $field = new xmldb_field('introformat', XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'intro');
        /// Launch add field introformat
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        // conditionally migrate to html format in intro
        if ($CFG->texteditors !== 'textarea') {
            $rs = $DB->get_recordset('forum', array('introformat' => FORMAT_MOODLE), '', 'id,intro,introformat');
            foreach ($rs as $f) {
                $f->intro = text_to_html($f->intro, false, false, true);
                $f->introformat = FORMAT_HTML;
                $DB->update_record('forum', $f);
                upgrade_set_timeout();
            }
            $rs->close();
        }
        /// forum savepoint reached
        upgrade_mod_savepoint(true, 2009042003, 'forum');
    }
    /// Dropping all enums/check contraints from core. MDL-18577
    if ($oldversion < 2009042700) {
        /// Changing list of values (enum) of field type on table forum to none
        $table = new xmldb_table('forum');
        $field = new xmldb_field('type', XMLDB_TYPE_CHAR, '20', null, XMLDB_NOTNULL, null, 'general', 'course');
        /// Launch change of list of values for field type
        $dbman->drop_enum_from_field($table, $field);
        /// forum savepoint reached
        upgrade_mod_savepoint(true, 2009042700, 'forum');
    }
    if ($oldversion < 2009050400) {
        /// Clean existing wrong rates. MDL-18227
        $DB->delete_records('forum_ratings', array('post' => 0));
        /// forum savepoint reached
        upgrade_mod_savepoint(true, 2009050400, 'forum');
    }
    if ($oldversion < 2010042800) {
        //migrate forumratings to the central rating table
        $table = new xmldb_table('forum_ratings');
        if ($dbman->table_exists($table)) {
            //forum ratings only have a single time column so use it for both time created and modified
            $sql = "INSERT INTO {rating} (contextid, scaleid, itemid, rating, userid, timecreated, timemodified)\n\n                    SELECT cxt.id, f.scale, r.post AS itemid, r.rating, r.userid, r.time AS timecreated, r.time AS timemodified\n                      FROM {forum_ratings} r\n                      JOIN {forum_posts} p ON p.id=r.post\n                      JOIN {forum_discussions} d ON d.id=p.discussion\n                      JOIN {forum} f ON f.id=d.forum\n                      JOIN {course_modules} cm ON cm.instance=f.id\n                      JOIN {context} cxt ON cxt.instanceid=cm.id\n                      JOIN {modules} m ON m.id=cm.module\n                     WHERE m.name = :modname AND cxt.contextlevel = :contextlevel";
            $params['modname'] = 'forum';
            $params['contextlevel'] = CONTEXT_MODULE;
            $DB->execute($sql, $params);
            //now drop forum_ratings
            $dbman->drop_table($table);
        }
        upgrade_mod_savepoint(true, 2010042800, 'forum');
    }
    if ($oldversion < 2010070800) {
        // Remove the forum digests message provider MDL-23145
        $DB->delete_records('message_providers', array('name' => 'digests', 'component' => 'mod_forum'));
        // forum savepoint reached
        upgrade_mod_savepoint(true, 2010070800, 'forum');
    }
    if ($oldversion < 2010091900) {
        // rename files from borked upgrade in 2.0dev
        $fs = get_file_storage();
        $rs = $DB->get_recordset('files', array('component' => 'mod_form'));
        foreach ($rs as $oldrecord) {
            $file = $fs->get_file_instance($oldrecord);
            $newrecord = array('component' => 'mod_forum');
            if (!$fs->file_exists($oldrecord->contextid, 'mod_forum', $oldrecord->filearea, $oldrecord->itemid, $oldrecord->filepath, $oldrecord->filename)) {
                $fs->create_file_from_storedfile($newrecord, $file);
            }
            $file->delete();
        }
        $rs->close();
        upgrade_mod_savepoint(true, 2010091900, 'forum');
    }
    return true;
}
Exemplo n.º 22
0
 /**
  * Regrade those questions in those attempts that are marked as needing regrading
  * in the quiz_overview_regrades table.
  * @param object $quiz the quiz settings.
  * @param array $groupstudents blank for all attempts, otherwise regrade attempts
  * for these users.
  */
 protected function regrade_attempts_needing_it($quiz, $groupstudents)
 {
     global $DB;
     $this->unlock_session();
     $where = "quiza.quiz = ? AND quiza.preview = 0 AND qqr.regraded = 0";
     $params = array($quiz->id);
     // Fetch all attempts that need regrading.
     if ($groupstudents) {
         list($usql, $uparams) = $DB->get_in_or_equal($groupstudents);
         $where .= " AND quiza.userid {$usql}";
         $params += $uparams;
     }
     $toregrade = $DB->get_records_sql("\n                SELECT quiza.uniqueid, qqr.slot\n                FROM {quiz_attempts} quiza\n                JOIN {quiz_overview_regrades} qqr ON qqr.questionusageid = quiza.uniqueid\n                WHERE {$where}", $params);
     if (!$toregrade) {
         return;
     }
     $attemptquestions = array();
     foreach ($toregrade as $row) {
         $attemptquestions[$row->uniqueid][] = $row->slot;
     }
     $attempts = $DB->get_records_list('quiz_attempts', 'uniqueid', array_keys($attemptquestions));
     $this->clear_regrade_table($quiz, $groupstudents);
     $progressbar = new progress_bar('quiz_overview_regrade', 500, true);
     $a = array('count' => count($attempts), 'done' => 0);
     foreach ($attempts as $attempt) {
         $this->regrade_attempt($attempt, false, $attemptquestions[$attempt->uniqueid]);
         $a['done']++;
         $progressbar->update($a['done'], $a['count'], get_string('regradingattemptxofy', 'quiz_overview', $a));
     }
     $this->update_overall_grades($quiz);
 }
Exemplo n.º 23
0
/**
 * Update all grades in gradebook.
 *
 * @global object
 */
function data_upgrade_grades() {
    global $DB;

    $sql = "SELECT COUNT('x')
              FROM {data} d, {course_modules} cm, {modules} m
             WHERE m.name='data' AND m.id=cm.module AND cm.instance=d.id";
    $count = $DB->count_records_sql($sql);

    $sql = "SELECT d.*, cm.idnumber AS cmidnumber, d.course AS courseid
              FROM {data} d, {course_modules} cm, {modules} m
             WHERE m.name='data' AND m.id=cm.module AND cm.instance=d.id";
    $rs = $DB->get_recordset_sql($sql);
    if ($rs->valid()) {
        // too much debug output
        $pbar = new progress_bar('dataupgradegrades', 500, true);
        $i=0;
        foreach ($rs as $data) {
            $i++;
            upgrade_set_timeout(60*5); // set up timeout, may also abort execution
            data_update_grades($data, 0, false);
            $pbar->update($i, $count, "Updating Database grades ($i/$count).");
        }
    }
    $rs->close();
}
Exemplo n.º 24
0
/**
 * Update all grades in gradebook.
 */
function scheduler_upgrade_grades()
{
    global $DB;
    $sql = "SELECT COUNT('x')\n        FROM {scheduler} s, {course_modules} cm, {modules} m\n        WHERE m.name='scheduler' AND m.id=cm.module AND cm.instance=s.id";
    $count = $DB->count_records_sql($sql);
    $sql = "SELECT s.*, cm.idnumber AS cmidnumber, s.course AS courseid\n        FROM {scheduler} s, {course_modules} cm, {modules} m\n        WHERE m.name='scheduler' AND m.id=cm.module AND cm.instance=s.id";
    $rs = $DB->get_recordset_sql($sql);
    if ($rs->valid()) {
        $pbar = new progress_bar('schedulerupgradegrades', 500, true);
        $i = 0;
        foreach ($rs as $scheduler) {
            $i++;
            upgrade_set_timeout(60 * 5);
            // Set up timeout, may also abort execution.
            scheduler_update_grades($scheduler);
            $pbar->update($i, $count, "Updating scheduler grades ({$i}/{$count}).");
        }
        upgrade_set_timeout();
        // Reset to default timeout.
    }
    $rs->close();
}
Exemplo n.º 25
0
/**
 * Update all grades in gradebook.
 */
function assignment_upgrade_grades() {
    global $DB;

    $sql = "SELECT COUNT('x')
              FROM {assignment} a, {course_modules} cm, {modules} m
             WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id";
    $count = $DB->count_records_sql($sql);

    $sql = "SELECT a.*, cm.idnumber AS cmidnumber, a.course AS courseid
              FROM {assignment} a, {course_modules} cm, {modules} m
             WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id";
    $rs = $DB->get_recordset_sql($sql);
    if ($rs->valid()) {
        // too much debug output
        $pbar = new progress_bar('assignmentupgradegrades', 500, true);
        $i=0;
        foreach ($rs as $assignment) {
            $i++;
            upgrade_set_timeout(60*5); // set up timeout, may also abort execution
            assignment_update_grades($assignment);
            $pbar->update($i, $count, "Updating Assignment grades ($i/$count).");
        }
        upgrade_set_timeout(); // reset to default timeout
    }
    $rs->close();
}
Exemplo n.º 26
0
/**
 * Update all grades in gradebook.
 */
function quiz_upgrade_grades() {
    global $DB;

    $sql = "SELECT COUNT('x')
              FROM {quiz} a, {course_modules} cm, {modules} m
             WHERE m.name='quiz' AND m.id=cm.module AND cm.instance=a.id";
    $count = $DB->count_records_sql($sql);

    $sql = "SELECT a.*, cm.idnumber AS cmidnumber, a.course AS courseid
              FROM {quiz} a, {course_modules} cm, {modules} m
             WHERE m.name='quiz' AND m.id=cm.module AND cm.instance=a.id";
    $rs = $DB->get_recordset_sql($sql);
    if ($rs->valid()) {
        $pbar = new progress_bar('quizupgradegrades', 500, true);
        $i=0;
        foreach ($rs as $quiz) {
            $i++;
            upgrade_set_timeout(60*5); // Set up timeout, may also abort execution.
            quiz_update_grades($quiz, 0, false);
            $pbar->update($i, $count, "Updating Quiz grades ($i/$count).");
        }
    }
    $rs->close();
}
Exemplo n.º 27
0
function xmldb_offlinequiz_upgrade($oldversion = 0)
{
    global $CFG, $THEME, $DB, $OUTPUT;
    $dbman = $DB->get_manager();
    // And upgrade begins here. For each one, you'll need one
    // Block of code similar to the next one. Please, delete
    // This comment lines once this file start handling proper
    // Upgrade code.
    // ONLY UPGRADE FROM Moodle 1.9.x (module version 2009042100) is supported.
    if ($oldversion < 2009120700) {
        // Define field counter to be added to offlinequiz_i_log.
        $table = new xmldb_table('offlinequiz_i_log');
        $field = new xmldb_field('counter');
        $field->set_attributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'rawdata');
        // Launch add field counter.
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        // Define field corners to be added to offlinequiz_i_log.
        $field = new xmldb_field('corners');
        $field->set_attributes(XMLDB_TYPE_CHAR, '50', null, null, null, null, 'counter');
        // Launch add field corners.
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        // Define field pdfintro to be added to offlinequiz.
        $table = new xmldb_table('offlinequiz');
        $field = new xmldb_field('pdfintro');
        $field->set_attributes(XMLDB_TYPE_TEXT, 'small', null, null, null, null, 'intro');
        // Launch add field pdfintro.
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        // Offlinequiz savepoint reached.
        upgrade_mod_savepoint(true, 2009120700, 'offlinequiz');
    }
    if ($oldversion < 2010082900) {
        // Define table offlinequiz_p_list to be created.
        $table = new xmldb_table('offlinequiz_p_list');
        // Adding fields to table offlinequiz_p_list.
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
        $table->add_field('offlinequiz', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0');
        $table->add_field('name', XMLDB_TYPE_CHAR, '255', null, null, null, null, null, null);
        $table->add_field('list', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '1');
        // Adding keys to table offlinequiz_p_list.
        $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
        // Launch create table for offlinequiz_p_list.
        $dbman->create_table($table);
        // Define field position to be dropped from offlinequiz_participants.
        $table = new xmldb_table('offlinequiz_participants');
        $field = new xmldb_field('position');
        // Launch drop field position.
        $dbman->drop_field($table, $field);
        // Define field page to be dropped from offlinequiz_participants.
        $table = new xmldb_table('offlinequiz_participants');
        $field = new xmldb_field('page');
        // Launch drop field page.
        $dbman->drop_field($table, $field);
        // Define field list to be added to offlinequiz_participants.
        $table = new xmldb_table('offlinequiz_participants');
        $field = new xmldb_field('list');
        $field->set_attributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '1', 'userid');
        // Launch add field list.
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        // Offlinequiz savepoint reached.
        upgrade_mod_savepoint(true, 2010082900, 'offlinequiz');
    }
    if ($oldversion < 2010090600) {
        // Define index offlinequiz (not unique) to be added to offlinequiz_p_list.
        $table = new xmldb_table('offlinequiz_p_list');
        $index = new XMLDBIndex('offlinequiz');
        $index->set_attributes(XMLDB_INDEX_NOTUNIQUE, array('offlinequiz'));
        // Launch add index offlinequiz.
        if (!$dbman->index_exists($table, $index)) {
            $dbman->add_index($table, $index);
        }
        $index = new XMLDBIndex('list');
        $index->set_attributes(XMLDB_INDEX_NOTUNIQUE, array('list'));
        // Launch add index list.
        if (!$dbman->index_exists($table, $index)) {
            $dbman->add_index($table, $index);
        }
        // Define index offlinequiz (not unique) to be added to offlinequiz_participants.
        $table = new xmldb_table('offlinequiz_participants');
        $index = new XMLDBIndex('offlinequiz');
        $index->set_attributes(XMLDB_INDEX_NOTUNIQUE, array('offlinequiz'));
        // Launch add index offlinequiz.
        if (!$dbman->index_exists($table, $index)) {
            $dbman->add_index($table, $index);
        }
        $index = new XMLDBIndex('list');
        $index->set_attributes(XMLDB_INDEX_NOTUNIQUE, array('list'));
        // Launch add index list.
        if (!$dbman->index_exists($table, $index)) {
            $dbman->add_index($table, $index);
        }
        $index = new XMLDBIndex('userid');
        $index->set_attributes(XMLDB_INDEX_NOTUNIQUE, array('userid'));
        // Launch add index list.
        if (!$dbman->index_exists($table, $index)) {
            $dbman->add_index($table, $index);
        }
        // Offlinequiz savepoint reached.
        upgrade_mod_savepoint(true, 2010090600, 'offlinequiz');
    }
    if ($oldversion < 2011021400) {
        // Define field fileformat to be added to offlinequiz.
        $table = new xmldb_table('offlinequiz');
        $field = new xmldb_field('fileformat');
        $field->set_attributes(XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'timemodified');
        // Launch add field fileformat.
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        // Offlinequiz savepoint reached.
        upgrade_mod_savepoint(true, 2011021400, 'offlinequiz');
    }
    if ($oldversion < 2011032900) {
        // Define field page to be added to offlinequiz_i_log.
        $table = new xmldb_table('offlinequiz_i_log');
        $field = new xmldb_field('page');
        $field->set_attributes(XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'corners');
        // Launch add field page.
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        // Define field username to be added to offlinequiz_i_log.
        $field = new xmldb_field('username');
        $field->set_attributes(XMLDB_TYPE_CHAR, '100', null, XMLDB_NOTNULL, null, null, 'page');
        // Launch add field username.
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        // Define index username (not unique) to be added to offlinequiz_i_log.
        $index = new XMLDBIndex('username');
        $index->set_attributes(XMLDB_INDEX_NOTUNIQUE, array('username'));
        // Launch add index username.
        if (!$dbman->index_exists($table, $index)) {
            $dbman->add_index($table, $index);
        }
        // Define field showgrades to be added to offlinequiz.
        $table = new xmldb_table('offlinequiz');
        $field = new xmldb_field('showgrades');
        $field->set_attributes(XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'fileformat');
        // Launch add field showgrades.
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        // Offlinequiz savepoint reached.
        upgrade_mod_savepoint(true, 2011032900, 'offlinequiz');
    }
    if ($oldversion < 2011081700) {
        // Define field showtutorial to be added to offlinequiz.
        $table = new xmldb_table('offlinequiz');
        $field = new xmldb_field('showtutorial');
        $field->set_attributes(XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'showgrades');
        // Launch add field showtutorial.
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        // Offlinequiz savepoint reached.
        upgrade_mod_savepoint(true, 2011081700, 'offlinequiz');
    }
    // ------------------------------------------------------
    // UPGRADE for Moodle 2.0 module starts here.
    // ------------------------------------------------------
    // First we do the changes to the main table 'offlinequiz'.
    // ------------------------------------------------------
    if ($oldversion < 2012010100) {
        // Define field docscreated to be added to offlinequiz.
        $table = new xmldb_table('offlinequiz');
        $field = new xmldb_field('docscreated', XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'questionsperpage');
        // Conditionally launch add field docscreated.
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        // Offlinequiz savepoint reached.
        upgrade_mod_savepoint(true, 2012010100, 'offlinequiz');
    }
    // Fill the new field docscreated.
    if ($oldversion < 2012010101) {
        $offlinequizzes = $DB->get_records('offlinequiz');
        foreach ($offlinequizzes as $offlinequiz) {
            $dirname = $CFG->dataroot . '/' . $offlinequiz->course . '/moddata/offlinequiz/' . $offlinequiz->id . '/pdfs';
            // If the answer pdf file for group 1 exists then we have created the documents.
            if (file_exists($dirname . '/answer-a.pdf')) {
                $DB->set_field('offlinequiz', 'docscreated', 1, array('id' => $offlinequiz->id));
            }
        }
        // Offlinequiz savepoint reached.
        upgrade_mod_savepoint(true, 2012010101, 'offlinequiz');
    }
    if ($oldversion < 2012010105) {
        // Define table offlinequiz_reports to be created.
        $table = new xmldb_table('offlinequiz_reports');
        // Adding fields to table offlinequiz_reports.
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
        $table->add_field('name', XMLDB_TYPE_CHAR, '255', null, null, null, null);
        $table->add_field('displayorder', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
        $table->add_field('lastcron', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0');
        $table->add_field('cron', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0');
        $table->add_field('capability', XMLDB_TYPE_CHAR, '255', null, null, null, null);
        // Adding keys to table offlinequiz_reports.
        $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
        // Adding indexes to table offlinequiz_reports.
        // $table->add_index('name', XMLDB_INDEX_UNIQUE, array('name'));.
        // Conditionally launch create table for offlinequiz_reports.
        if (!$dbman->table_exists($table)) {
            $dbman->create_table($table);
        }
        if (!$DB->get_records_sql("SELECT * FROM {offlinequiz_reports} WHERE name = 'overview'", array())) {
            $record = new stdClass();
            $record->name = 'overview';
            $record->displayorder = '10000';
            $DB->insert_record('offlinequiz_reports', $record);
        }
        if (!$DB->get_records_sql("SELECT * FROM {offlinequiz_reports} WHERE name = 'rimport'", array())) {
            $record = new stdClass();
            $record->name = 'rimport';
            $record->displayorder = '9000';
            $DB->insert_record('offlinequiz_reports', $record);
        }
        // Offlinequiz savepoint reached.
        upgrade_mod_savepoint(true, 2012010105, 'offlinequiz');
    }
    // Now we create all the new tables.
    // Create table offlinequiz_groups.
    if ($oldversion < 2012010200) {
        echo $OUTPUT->notification('Creating new tables', 'notifysuccess');
        // Define table offlinequiz_groups to be created.
        $table = new xmldb_table('offlinequiz_groups');
        // Adding fields to table offlinequiz_groups.
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
        $table->add_field('offlinequizid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
        $table->add_field('number', XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0');
        $table->add_field('sumgrades', XMLDB_TYPE_NUMBER, '10, 5', null, XMLDB_NOTNULL, null, '0');
        $table->add_field('numberofpages', XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0');
        $table->add_field('templateusageid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0');
        // Adding keys to table offlinequiz_groups.
        $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
        // Adding indexes to table offlinequiz_groups.
        $table->add_index('offlinequizid', XMLDB_INDEX_NOTUNIQUE, array('offlinequizid'));
        // Conditionally launch create table for offlinequiz_groups.
        if (!$dbman->table_exists($table)) {
            $dbman->create_table($table);
        }
        // Offlinequiz savepoint reached.
        upgrade_mod_savepoint(true, 2012010200, 'offlinequiz');
    }
    // Create table offlinequiz_group_questions.
    if ($oldversion < 2012010300) {
        // Define table offlinequiz_group_questions to be created.
        $table = new xmldb_table('offlinequiz_group_questions');
        // Adding fields to table offlinequiz_group_questions.
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
        $table->add_field('offlinequizid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
        $table->add_field('offlinegroupid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
        $table->add_field('questionid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
        $table->add_field('position', XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '1');
        $table->add_field('pagenumber', XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, null, null, null);
        $table->add_field('usageslot', XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, null, null, null);
        // Adding keys to table offlinequiz_group_questions.
        $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
        // Adding indexes to table offlinequiz_group_questions.
        $table->add_index('offlinequiz', XMLDB_INDEX_NOTUNIQUE, array('offlinequizid'));
        // Conditionally launch create table for offlinequiz_group_questions.
        if (!$dbman->table_exists($table)) {
            $dbman->create_table($table);
        }
        // Offlinequiz savepoint reached.
        upgrade_mod_savepoint(true, 2012010300, 'offlinequiz');
    }
    if ($oldversion < 2012010400) {
        // Define table offlinequiz_scanned_pages to be created.
        $table = new xmldb_table('offlinequiz_scanned_pages');
        // Adding fields to table offlinequiz_scanned_pages.
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
        $table->add_field('offlinequizid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
        $table->add_field('resultid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null);
        $table->add_field('filename', XMLDB_TYPE_CHAR, '1000', null, null, null, null);
        $table->add_field('warningfilename', XMLDB_TYPE_CHAR, '1000', null, null, null, null);
        $table->add_field('groupnumber', XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, null, null, null);
        $table->add_field('userkey', XMLDB_TYPE_CHAR, '255', null, null, null, null);
        $table->add_field('pagenumber', XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, null, null, null);
        $table->add_field('time', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0');
        $table->add_field('status', XMLDB_TYPE_CHAR, '20', null, XMLDB_NOTNULL, null, null);
        $table->add_field('error', XMLDB_TYPE_CHAR, '255', null, null, null, null);
        $table->add_field('info', XMLDB_TYPE_TEXT, 'medium', null, null, null, null);
        // Adding keys to table offlinequiz_scanned_pages.
        $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
        // Adding indexes to table offlinequiz_scanned_pages.
        $table->add_index('offlinequizid', XMLDB_INDEX_NOTUNIQUE, array('offlinequizid'));
        // Conditionally launch create table for offlinequiz_scanned_pages.
        if (!$dbman->table_exists($table)) {
            $dbman->create_table($table);
        }
        // Offlinequiz savepoint reached.
        upgrade_mod_savepoint(true, 2012010400, 'offlinequiz');
    }
    if ($oldversion < 2012010500) {
        // Define table offlinequiz_choices to be created.
        $table = new xmldb_table('offlinequiz_choices');
        // Adding fields to table offlinequiz_choices.
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
        $table->add_field('scannedpageid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
        $table->add_field('slotnumber', XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
        $table->add_field('choicenumber', XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
        $table->add_field('value', XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, null);
        // Adding keys to table offlinequiz_choices.
        $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
        // Adding indexes to table offlinequiz_choices.
        $table->add_index('scannedpageid', XMLDB_INDEX_NOTUNIQUE, array('scannedpageid'));
        // Conditionally launch create table for offlinequiz_choices.
        if (!$dbman->table_exists($table)) {
            $dbman->create_table($table);
        }
        // Offlinequiz savepoint reached.
        upgrade_mod_savepoint(true, 2012010500, 'offlinequiz');
    }
    if ($oldversion < 2012010600) {
        // Define table offlinequiz_page_corners to be created.
        $table = new xmldb_table('offlinequiz_page_corners');
        // Adding fields to table offlinequiz_page_corners.
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
        $table->add_field('scannedpageid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
        $table->add_field('x', XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0');
        $table->add_field('y', XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0');
        $table->add_field('position', XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
        // Adding keys to table offlinequiz_page_corners.
        $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
        // Conditionally launch create table for offlinequiz_page_corners.
        if (!$dbman->table_exists($table)) {
            $dbman->create_table($table);
        }
        // Offlinequiz savepoint reached.
        upgrade_mod_savepoint(true, 2012010600, 'offlinequiz');
    }
    if ($oldversion < 2012010700) {
        // Define table offlinequiz_results to be created.
        $table = new xmldb_table('offlinequiz_results');
        // Adding fields to table offlinequiz_results.
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
        $table->add_field('offlinequizid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
        $table->add_field('offlinegroupid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
        $table->add_field('userid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
        $table->add_field('sumgrades', XMLDB_TYPE_NUMBER, '10, 5', null, null, null, null);
        $table->add_field('usageid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
        $table->add_field('teacherid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
        $table->add_field('attendant', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null);
        $table->add_field('status', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null);
        $table->add_field('timestart', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0');
        $table->add_field('timefinish', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, '0');
        $table->add_field('timemodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0');
        $table->add_field('preview', XMLDB_TYPE_INTEGER, '3', XMLDB_UNSIGNED, null, null, '0');
        // Adding keys to table offlinequiz_results.
        $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
        // Conditionally launch create table for offlinequiz_results.
        if (!$dbman->table_exists($table)) {
            $dbman->create_table($table);
        }
        // Offlinequiz savepoint reached.
        upgrade_mod_savepoint(true, 2012010700, 'offlinequiz');
    }
    if ($oldversion < 2012010800) {
        // Define table offlinequiz_scanned_p_pages to be created.
        $table = new xmldb_table('offlinequiz_scanned_p_pages');
        // Adding fields to table offlinequiz_scanned_p_pages.
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
        $table->add_field('offlinequizid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
        $table->add_field('listnumber', XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, null, null, null);
        $table->add_field('filename', XMLDB_TYPE_CHAR, '1000', null, null, null, null);
        $table->add_field('time', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0');
        $table->add_field('status', XMLDB_TYPE_TEXT, 'small', null, XMLDB_NOTNULL, null);
        $table->add_field('error', XMLDB_TYPE_TEXT, 'small', null, null, null, null);
        // Adding keys to table offlinequiz_scanned_p_pages.
        $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
        // Conditionally launch create table for offlinequiz_scanned_p_pages.
        if (!$dbman->table_exists($table)) {
            $dbman->create_table($table);
        }
        // Offlinequiz savepoint reached.
        upgrade_mod_savepoint(true, 2012010800, 'offlinequiz');
    }
    if ($oldversion < 2012010900) {
        // Define table offlinequiz_p_choices to be created.
        $table = new xmldb_table('offlinequiz_p_choices');
        // Adding fields to table offlinequiz_p_choices.
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
        $table->add_field('scannedppageid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
        $table->add_field('userid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null);
        $table->add_field('value', XMLDB_TYPE_INTEGER, '4', null, XMLDB_NOTNULL, null, '0');
        // Adding keys to table offlinequiz_p_choices.
        $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
        // Conditionally launch create table for offlinequiz_p_choices.
        if (!$dbman->table_exists($table)) {
            $dbman->create_table($table);
        }
        // Offlinequiz savepoint reached.
        upgrade_mod_savepoint(true, 2012010900, 'offlinequiz');
    }
    if ($oldversion < 2012011000) {
        // Define table offlinequiz_p_lists to be created.
        $table = new xmldb_table('offlinequiz_p_lists');
        // Adding fields to table offlinequiz_p_lists.
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
        $table->add_field('offlinequizid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0');
        $table->add_field('name', XMLDB_TYPE_CHAR, '255', null, null, null, null);
        $table->add_field('number', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '1');
        $table->add_field('filename', XMLDB_TYPE_CHAR, '1000', null, null, null, null);
        // Adding keys to table offlinequiz_p_lists.
        $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
        // Adding indexes to table offlinequiz_p_lists.
        $table->add_index('offlinequizid', XMLDB_INDEX_NOTUNIQUE, array('offlinequizid'));
        // Conditionally launch create table for offlinequiz_p_lists.
        if (!$dbman->table_exists($table)) {
            $dbman->create_table($table);
        }
        // Offlinequiz savepoint reached.
        upgrade_mod_savepoint(true, 2012011000, 'offlinequiz');
    }
    // ------------------------------------------------------
    // New we rename fields in old tables.
    // ------------------------------------------------------
    // Rename fields in offlinequiz_queue table.
    if ($oldversion < 2012020100) {
        echo $OUTPUT->notification('Renaming fields in old tables.', 'notifysuccess');
        // Rename field offlinequiz on table offlinequiz_queue to NEWNAMEGOESHERE.
        $table = new xmldb_table('offlinequiz_queue');
        $field = new xmldb_field('offlinequiz');
        $field->set_attributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'timefinish');
        // Launch rename field offlinequiz.
        $dbman->rename_field($table, $field, 'offlinequizid');
        $field = new xmldb_field('importadmin');
        $field->set_attributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'id');
        // Launch rename field importadmin.
        $dbman->rename_field($table, $field, 'importuserid');
        // New status field.
        $field = new xmldb_field('status', XMLDB_TYPE_TEXT, 'small', null, null, null, 'processed', 'timefinish');
        // Conditionally launch add field status.
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        // Offlinequiz savepoint reached.
        upgrade_mod_savepoint(true, 2012020100, 'offlinequiz');
    }
    // Add and rename fields in table offlinquiz_queue_data.
    if ($oldversion < 2012020200) {
        // Define field status to be added to offlinequiz_queue_data.
        $table = new xmldb_table('offlinequiz_queue_data');
        $field = new xmldb_field('status', XMLDB_TYPE_TEXT, 'small', null, XMLDB_NOTNULL, null, 'ok', 'filename');
        // Conditionally launch add field status.
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        } else {
            $dbman->change_field_type($table, $field);
            $dbman->change_field_precision($table, $field);
            $dbman->change_field_notnull($table, $field);
            $dbman->change_field_unsigned($table, $field);
        }
        // Add new field 'error'.
        $field = new xmldb_field('error', XMLDB_TYPE_TEXT, 'small', null, null, null, null, 'status');
        // Conditionally launch add field error.
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        // Rename field queue to queueid.
        $field = new xmldb_field('queue', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'id');
        // Launch rename field queueid.
        $dbman->rename_field($table, $field, 'queueid');
        // Offlinequiz savepoint reached.
        upgrade_mod_savepoint(true, 2012020200, 'offlinequiz');
    }
    // Rename field list on table offlinequiz_participants to listid.
    if ($oldversion < 2012020300) {
        // Rename field list on table offlinequiz_participants to listid.
        $table = new xmldb_table('offlinequiz_participants');
        $field = new xmldb_field('list', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'id');
        // Launch rename field listid.
        $dbman->rename_field($table, $field, 'listid');
        // Offlinequiz savepoint reached.
        upgrade_mod_savepoint(true, 2012020300, 'offlinequiz');
    }
    // Migrate the old lists of participants to the new table offlinequiz_p_lists (with 's').
    if ($oldversion < 2012020400) {
        $oldplists = $DB->get_records('offlinequiz_p_list');
        foreach ($oldplists as $oldplist) {
            $newplist = new StdClass();
            $newplist->offlinequizid = $oldplist->offlinequiz;
            $newplist->name = $oldplist->name;
            $newplist->number = $oldplist->list;
            // NOTE.
            // We don't set filename because we can always recreate the PDF files if needed.
            $newplist->id = $DB->insert_record('offlinequiz_p_lists', $newplist);
            // Get all the participants linked to the old list and link them to the new list in offlinequiz_p_lists.
            if ($oldparts = $DB->get_records('offlinequiz_participants', array('listid' => $oldplist->id))) {
                foreach ($oldparts as $oldpart) {
                    $oldpart->listid = $newplist->id;
                    $DB->update_record('offlinequiz_participants', $oldpart);
                }
            }
        }
        // Offlinequiz savepoint reached.
        upgrade_mod_savepoint(true, 2012020400, 'offlinequiz');
    }
    // Check if there are inconsistencies in the DB, i.e. uniqueids used by both quizzes and offlinequizzes.
    if ($oldversion < 2012020410) {
        $sql = 'SELECT uniqueid
        FROM {offlinequiz_attempts} qa WHERE
        EXISTS (SELECT id from {quiz_attempts} where uniqueid = qa.uniqueid)';
        $doubleids = $DB->get_fieldset_sql($sql, array());
        // For each double uniqueid create a new uniqueid and change the fields in the tables.
        // Offlinequiz_attempts, question_sessions and question_states.
        echo $OUTPUT->notification('Fixing ' . count($doubleids) . ' question attempt uniqueids that are not unique', 'notifysuccess');
        foreach ($doubleids as $doubleid) {
            echo $doubleid . ', ';
            if ($usage = $DB->get_record('question_usages', array('id' => $doubleid))) {
                $transaction = $DB->start_delegated_transaction();
                unset($usage->id);
                $usage->id = $DB->insert_record('question_usages', $usage);
                $DB->set_field_select('offlinequiz_attempts', 'uniqueid', $usage->id, 'uniqueid = :oldid', array('oldid' => $doubleid));
                $DB->set_field_select('question_states', 'attempt', $usage->id, 'attempt = :oldid', array('oldid' => $doubleid));
                $DB->set_field_select('question_sessions', 'attemptid', $usage->id, 'attemptid = :oldid', array('oldid' => $doubleid));
                $transaction->allow_commit();
            }
        }
        upgrade_mod_savepoint(true, 2012020410, 'offlinequiz');
    }
    // -----------------------------------------------------
    //  Update the contextid field in question_usages (compare lib/db/upgrade.php lines 6108 following).
    // -----------------------------------------------------
    if ($oldversion < 2012020500) {
        echo $OUTPUT->notification('Fixing question usages context ID', 'notifysuccess');
        // Update the component field if necessary.
        $DB->set_field('question_usages', 'component', 'mod_offlinequiz', array('component' => 'offlinequiz'));
        // Populate the contextid field.
        $offlinequizmoduleid = $DB->get_field('modules', 'id', array('name' => 'offlinequiz'));
        $DB->execute("\n                UPDATE {question_usages} SET contextid = (\n                SELECT ctx.id\n                FROM {context} ctx\n                JOIN {course_modules} cm ON cm.id = ctx.instanceid AND cm.module = {$offlinequizmoduleid}\n                JOIN {offlinequiz_attempts} quiza ON quiza.offlinequiz = cm.instance\n                WHERE ctx.contextlevel = " . CONTEXT_MODULE . "\n                AND quiza.uniqueid = {question_usages}.id)\n                WHERE (\n                SELECT ctx.id\n                FROM {context} ctx\n                JOIN {course_modules} cm ON cm.id = ctx.instanceid AND cm.module = {$offlinequizmoduleid}\n                JOIN {offlinequiz_attempts} quiza ON quiza.offlinequiz = cm.instance\n                WHERE ctx.contextlevel = " . CONTEXT_MODULE . "\n                AND quiza.uniqueid = {question_usages}.id) IS NOT NULL\n                ");
        // Offlinequiz savepoint reached.
        upgrade_mod_savepoint(true, 2012020500, 'offlinequiz');
    }
    // -----------------------------------------------------
    //  Now we migrate data from the old to the new tables.
    // -----------------------------------------------------
    // We have to delete redundant question instances from offlinequizzes because they are incompatible with the new code.
    if ($oldversion < 2012030100) {
        echo $OUTPUT->notification('Migrating old offline quizzes to new offline quizzes..', 'notifysuccess');
        require_once $CFG->dirroot . '/mod/offlinequiz/db/upgradelib.php';
        offlinequiz_remove_redundant_q_instances();
        // Offlinequiz savepoint reached.
        upgrade_mod_savepoint(true, 2012030100, 'offlinequiz');
    }
    // Migrate all entries in the offlinequiz_group table to the new tables offlinequiz_groups  and offlinequiz_group_questions.
    if ($oldversion < 2012030101) {
        echo $OUTPUT->notification('Creating new offlinequiz groups', 'notifysuccess');
        $offlinequizzes = $DB->get_records('offlinequiz');
        $counter = 0;
        foreach ($offlinequizzes as $offlinequiz) {
            if (!$DB->get_records('offlinequiz_groups', array('offlinequizid' => $offlinequiz->id))) {
                echo '.';
                $counter++;
                flush();
                ob_flush();
                if ($counter % 100 == 0) {
                    echo "<br/>\n";
                    echo $counter;
                }
                $transaction = $DB->start_delegated_transaction();
                $oldgroups = $DB->get_records('offlinequiz_group', array('offlinequiz' => $offlinequiz->id), 'groupid ASC');
                $newgroups = array();
                foreach ($oldgroups as $oldgroup) {
                    $newgroup = new StdClass();
                    $newgroup->offlinequizid = $offlinequiz->id;
                    $newgroup->number = $oldgroup->groupid;
                    $newgroup->sumgrades = $oldgroup->sumgrades;
                    $newgroup->timecreated = time();
                    $newgroup->timemodified = time();
                    // First we need the ID of the new group.
                    if (!($oldid = $DB->get_field('offlinequiz_groups', 'id', array('offlinequizid' => $offlinequiz->id, 'number' => $newgroup->number)))) {
                        $newgroup->id = $DB->insert_record('offlinequiz_groups', $newgroup);
                    } else {
                        $newgroup->id = $oldid;
                    }
                    // Now create an entry in offlinquiz_group_questions for each question in the old group layout.
                    $questions = explode(',', $oldgroup->questions);
                    $position = 1;
                    foreach ($questions as $question) {
                        $groupquestion = new StdClass();
                        $groupquestion->offlinequizid = $offlinequiz->id;
                        $groupquestion->offlinegroupid = $newgroup->id;
                        $groupquestion->questionid = $question;
                        $groupquestion->position = $position++;
                        if (!$DB->get_record('offlinequiz_group_questions', array('offlinequizid' => $offlinequiz->id, 'offlinegroupid' => $newgroup->id, 'questionid' => $question))) {
                            $DB->insert_record('offlinequiz_group_questions', $groupquestion);
                        }
                    }
                    $newgroups[] = $newgroup;
                }
                require_once $CFG->dirroot . '/mod/offlinequiz/evallib.php';
                list($maxquestions, $maxanswers, $formtype, $questionsperpage) = offlinequiz_get_question_numbers($offlinequiz, $newgroups);
                foreach ($newgroups as $newgroup) {
                    // Now we know the number of pages of the group.
                    $newgroup->numberofpages = ceil($maxquestions / ($formtype * 24));
                    $DB->update_record('offlinequiz_groups', $newgroup);
                }
                $transaction->allow_commit();
            }
        }
        // Offlinequiz savepoint reached.
        upgrade_mod_savepoint(true, 2012030101, 'offlinequiz');
    }
    // Migrate all entries in the offlinequiz_i_log table to the new tables offlinequiz_scanned_pages, offlinequiz_choices and.
    // Offlinequiz_page_corners. Also migrate the files to the new filesystem.
    // First we mark all offlinequizzes s.t. we upgrade them only once. Many things can go wrong here..
    if ($oldversion < 2012030200) {
        // Define field needsilogupgrade to be added to offlinequiz_attempts.
        $table = new xmldb_table('offlinequiz');
        $field = new xmldb_field('needsilogupgrade', XMLDB_TYPE_INTEGER, '3', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'timeopen');
        // Launch add field needsilogupgrade.
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        $DB->set_field('offlinequiz', 'needsilogupgrade', 1);
        // Offlinequiz savepoint reached.
        upgrade_mod_savepoint(true, 2012030200, 'offlinequiz');
    }
    // Then we mark all offlinequiz_attempts to be upgraded.
    if ($oldversion < 2012030300) {
        // Define field needsupgradetonewqe to be added to offlinequiz_attempts.
        $table = new xmldb_table('offlinequiz_attempts');
        $field = new xmldb_field('needsupgradetonewqe', XMLDB_TYPE_INTEGER, '3', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'sheet');
        // Launch add field needsupgradetonewqe.
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        $DB->set_field('offlinequiz_attempts', 'needsupgradetonewqe', 1);
        // Quiz savepoint reached.
        upgrade_mod_savepoint(true, 2012030300, 'offlinequiz');
    }
    // In a first step we upgrade the offlinequiz_attempts exactly like quiz_attempts (see mod/quiz/db/upgrade.php).
    if ($oldversion < 2012030400) {
        $table = new xmldb_table('question_states');
        // Echo "upgrading attempts to new question engine <br/>\n";.
        if ($dbman->table_exists($table)) {
            // NOTE: We need all attemps, also the ones with sheet=1 because the are the groups' template attempts.
            // Now update all the old attempt data.
            $oldrcachesetting = $CFG->rcache;
            $CFG->rcache = false;
            require_once $CFG->dirroot . '/mod/offlinequiz/db/upgradelib.php';
            $upgrader = new offlinequiz_attempt_upgrader();
            $upgrader->convert_all_quiz_attempts();
            $CFG->rcache = $oldrcachesetting;
        }
        // Offlinequiz savepoint reached.
        upgrade_mod_savepoint(true, 2012030400, 'offlinequiz');
    }
    // Then we mark all offlinequiz_attempts to be upgraded.
    if ($oldversion < 2012030500) {
        // Define field resultid to be added to offlinequiz_attempts for later reference.
        set_time_limit(3000);
        $table = new xmldb_table('offlinequiz_attempts');
        $field = new xmldb_field('resultid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0');
        // Launch add field resultid.
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        // Quiz savepoint reached.
        upgrade_mod_savepoint(true, 2012030500, 'offlinequiz');
    }
    // In a second step we convert all offlinequiz_attempts into offlinequiz_results and also upgrade the ilog table.
    if ($oldversion < 2012060101) {
        require_once $CFG->dirroot . '/mod/offlinequiz/db/upgradelib.php';
        $oldrcachesetting = $CFG->rcache;
        $CFG->rcache = false;
        $upgrader = new offlinequiz_ilog_upgrader();
        $upgrader->convert_all_offlinequiz_attempts();
        $CFG->rcache = $oldrcachesetting;
        // Offlinequiz savepoint reached.
        upgrade_mod_savepoint(true, 2012060101, 'offlinequiz');
    }
    if ($oldversion < 2012060105) {
        // Changing type of field grade on table offlinequiz_q_instances to number.
        $table = new xmldb_table('offlinequiz_q_instances');
        $field = new xmldb_field('grade', XMLDB_TYPE_NUMBER, '12, 7', null, XMLDB_NOTNULL, null, '0', 'question');
        // Launch change of type for field grade.
        $dbman->change_field_type($table, $field);
        // Launch change of precision for field grade.
        $dbman->change_field_precision($table, $field);
        // Offlinequiz savepoint reached.
        upgrade_mod_savepoint(true, 2012060105, 'offlinequiz');
    }
    if ($oldversion < 2012121200) {
        // Define field introformat to be added to offlinequiz.
        $table = new xmldb_table('offlinequiz');
        $field = new xmldb_field('introformat', XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'intro');
        // Conditionally launch add field introformat.
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        // Offlinequiz savepoint reached.
        upgrade_mod_savepoint(true, 2012121200, 'offlinequiz');
    }
    if ($oldversion < 2013012400) {
        // Define field info to be added to offlinequiz_queue.
        $table = new xmldb_table('offlinequiz_queue');
        $field = new xmldb_field('info', XMLDB_TYPE_TEXT, 'medium', null, null, null, null, 'status');
        // Conditionally launch add field info.
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        // Offlinequiz savepoint reached.
        upgrade_mod_savepoint(true, 2013012400, 'offlinequiz');
    }
    if ($oldversion < 2013012410) {
        // Define field info to be added to offlinequiz_queue_data.
        $table = new xmldb_table('offlinequiz_queue_data');
        $field = new xmldb_field('info', XMLDB_TYPE_TEXT, 'medium', null, null, null, null, 'error');
        // Conditionally launch add field info.
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        // Offlinequiz savepoint reached.
        upgrade_mod_savepoint(true, 2013012410, 'offlinequiz');
    }
    if ($oldversion < 2013012500) {
        // Changing type of field grade on table offlinequiz to int.
        $table = new xmldb_table('offlinequiz');
        $field = new xmldb_field('grade', XMLDB_TYPE_NUMBER, '10, 5', null, XMLDB_NOTNULL, null, '0', 'time');
        // Launch change for field grade.
        $dbman->change_field_type($table, $field);
        $dbman->change_field_precision($table, $field);
        $dbman->change_field_unsigned($table, $field);
        // Offlinequiz savepoint reached.
        upgrade_mod_savepoint(true, 2013012500, 'offlinequiz');
    }
    if ($oldversion < 2013041600) {
        // Rename field question on table offlinequiz_q_instances to questionid.
        $table = new xmldb_table('offlinequiz_q_instances');
        $field = new xmldb_field('question', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, 'offlinequiz');
        // Launch rename field question.
        $dbman->rename_field($table, $field, 'questionid');
        // Offlinequiz savepoint reached.
        upgrade_mod_savepoint(true, 2013041600, 'offlinequiz');
    }
    if ($oldversion < 2013041601) {
        // Rename field offlinequiz on table offlinequiz_q_instances to offlinequizid.
        $table = new xmldb_table('offlinequiz_q_instances');
        $field = new xmldb_field('offlinequiz', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, 'id');
        // Launch rename field offlinequiz.
        $dbman->rename_field($table, $field, 'offlinequizid');
        // Offlinequiz savepoint reached.
        upgrade_mod_savepoint(true, 2013041601, 'offlinequiz');
    }
    if ($oldversion < 2013061300) {
        // Define table offlinequiz_hotspots to be created.
        $table = new xmldb_table('offlinequiz_hotspots');
        // Adding fields to table offlinequiz_hotspots.
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
        $table->add_field('scannedpageid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null);
        $table->add_field('name', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null);
        $table->add_field('x', XMLDB_TYPE_NUMBER, '10, 2', null, XMLDB_NOTNULL, null, null);
        $table->add_field('y', XMLDB_TYPE_NUMBER, '10, 2', null, XMLDB_NOTNULL, null, null);
        $table->add_field('blank', XMLDB_TYPE_INTEGER, '1', null, null, null, null);
        $table->add_field('time', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
        // Adding keys to table offlinequiz_hotspots.
        $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
        // Adding indexes to table offlinequiz_hotspots.
        $table->add_index('scannedpageididx', XMLDB_INDEX_NOTUNIQUE, array('scannedpageid'));
        // Conditionally launch create table for offlinequiz_hotspots.
        if (!$dbman->table_exists($table)) {
            $dbman->create_table($table);
        }
        // Offlinequiz savepoint reached.
        upgrade_mod_savepoint(true, 2013061300, 'offlinequiz');
    }
    if ($oldversion < 2013110800) {
        // Define field timecreated to be added to offlinequiz_queue.
        $table = new xmldb_table('offlinequiz_queue');
        $field = new xmldb_field('timecreated', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0', 'importuserid');
        // Conditionally launch add field timecreated.
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        // Offlinequiz savepoint reached.
        upgrade_mod_savepoint(true, 2013110800, 'offlinequiz');
    }
    if ($oldversion < 2013112500) {
        // Define index offlinequiz_userid_idx (not unique) to be added to offlinequiz_results.
        $table = new xmldb_table('offlinequiz_results');
        $index = new xmldb_index('offlinequiz_userid_idx', XMLDB_INDEX_NOTUNIQUE, array('userid'));
        // Conditionally launch add index offlinequiz_userid_idx.
        if (!$dbman->index_exists($table, $index)) {
            $dbman->add_index($table, $index);
        }
        // Offlinequiz savepoint reached.
        upgrade_mod_savepoint(true, 2013112500, 'offlinequiz');
    }
    // Moodle v2.8.5+ release upgrade line.
    // Put any upgrade step following this.
    if ($oldversion < 2015060500) {
        // Rename field page on table offlinequiz_group_questions to NEWNAMEGOESHERE.
        $table = new xmldb_table('offlinequiz_group_questions');
        $field = new xmldb_field('pagenumber', XMLDB_TYPE_INTEGER, '4', null, null, null, null, 'position');
        // Launch rename field page.
        $dbman->rename_field($table, $field, 'page');
        // Offlinequiz savepoint reached.
        upgrade_mod_savepoint(true, 2015060500, 'offlinequiz');
    }
    if ($oldversion < 2015060501) {
        // Rename field page on table offlinequiz_group_questions to NEWNAMEGOESHERE.
        $table = new xmldb_table('offlinequiz_group_questions');
        $field = new xmldb_field('usageslot', XMLDB_TYPE_INTEGER, '4', null, null, null, null, 'position');
        // Launch rename field page.
        $dbman->rename_field($table, $field, 'slot');
        // Offlinequiz savepoint reached.
        upgrade_mod_savepoint(true, 2015060501, 'offlinequiz');
    }
    if ($oldversion < 2015060502) {
        // Define field maxmark to be added to offlinequiz_group_questions.
        $table = new xmldb_table('offlinequiz_group_questions');
        $field = new xmldb_field('maxmark', XMLDB_TYPE_NUMBER, '12, 7', null, XMLDB_NOTNULL, null, '1', 'slot');
        // Conditionally launch add field maxmark.
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        // Offlinequiz savepoint reached.
        upgrade_mod_savepoint(true, 2015060502, 'offlinequiz');
    }
    if ($oldversion < 2015060902) {
        // This upgrade migrates old offlinequiz_q_instances grades (maxgrades) to new
        // maxmark field in offlinequiz_group_questions.
        // It also deletes group questions with questionid 0 (pagebreaks) and inserts the
        // correct page number instead.
        $numofflinequizzes = $DB->count_records('offlinequiz');
        if ($numofflinequizzes > 0) {
            $pbar = new progress_bar('offlinequizquestionstoslots', 500, true);
            $pbar->create();
            $pbar->update(0, $numofflinequizzes, "Upgrading offlinequiz group questions - {0}/{$numofflinequizzes}.");
            $numberdone = 0;
            $offlinequizzes = $DB->get_recordset('offlinequiz', null, 'id', 'id, numgroups');
            foreach ($offlinequizzes as $offlinequiz) {
                $transaction = $DB->start_delegated_transaction();
                $groups = $DB->get_records('offlinequiz_groups', array('offlinequizid' => $offlinequiz->id), 'number', '*');
                $instancesraw = $DB->get_records('offlinequiz_q_instances', array('offlinequizid' => $offlinequiz->id));
                $questioninstances = array();
                foreach ($instancesraw as $instance) {
                    if (!array_key_exists($instance->questionid, $questioninstances)) {
                        $questioninstances[$instance->questionid] = $instance;
                    }
                }
                foreach ($groups as $group) {
                    $groupquestions = $DB->get_records('offlinequiz_group_questions', array('offlinequizid' => $offlinequiz->id, 'offlinegroupid' => $group->id), 'position');
                    // For every group we start on page 1.
                    $currentpage = 1;
                    $currentslot = 1;
                    foreach ($groupquestions as $groupquestion) {
                        $needsupdate = false;
                        if ($groupquestion->questionid == 0) {
                            // We remove the old pagebreaks with questionid==0.
                            $DB->delete_records('offlinequiz_group_questions', array('id' => $groupquestion->id));
                            $currentpage++;
                            continue;
                        }
                        // If the maxmarks in the question instances differs from the default maxmark (1)
                        // of the offlinequiz_group_questions then change it.
                        if (array_key_exists($groupquestion->questionid, $questioninstances) && ($maxmark = floatval($questioninstances[$groupquestion->questionid]->grade)) && abs(floatval($groupquestion->maxmark) - $maxmark) > 0.001) {
                            $groupquestion->maxmark = $maxmark;
                            $needsupdate = true;
                        }
                        // If the page number is not correct, then change it.
                        if ($groupquestion->page != $currentpage) {
                            $groupquestion->page = $currentpage;
                            $needsupdate = true;
                        }
                        // If the slot is not set, then fill it.
                        if (!$groupquestion->slot) {
                            $groupquestion->slot = $currentslot;
                            $needsupdate = true;
                        }
                        if ($needsupdate) {
                            $DB->update_record('offlinequiz_group_questions', $groupquestion);
                        }
                        $currentslot++;
                    }
                }
                // Done with this offlinequiz. Update progress bar.
                $numberdone++;
                $pbar->update($numberdone, $numofflinequizzes, "Upgrading offlinequiz group questions - {$numberdone}/{$numofflinequizzes}.");
                $transaction->allow_commit();
            }
        }
        // Offlinequiz savepoint reached.
        upgrade_mod_savepoint(true, 2015060902, 'offlinequiz');
    }
    // TODO migrate old offlinequiz_q_instances maxmarks to new maxmark field in offlinequiz_group_questions.
    // TODO migrate  offlinequiz_group_questions to fill in page field correctly. For every group use the
    //      position field to find new pages and insert them.
    //      Adapt offlinequiz code to handle missing zeros as pagebreaks.
    return true;
}
Exemplo n.º 28
0
function xmldb_glossary_upgrade($oldversion) {
    global $CFG, $DB, $OUTPUT;

    $dbman = $DB->get_manager();

//===== 1.9.0 upgrade line ======//

    if ($oldversion < 2008081900) {

        /////////////////////////////////////
        /// new file storage upgrade code ///
        /////////////////////////////////////

        $fs = get_file_storage();

        $empty = $DB->sql_empty(); // silly oracle empty string handling workaround

        $sqlfrom = "FROM {glossary_entries} ge
                    JOIN {glossary} g ON g.id = ge.glossaryid
                    JOIN {modules} m ON m.name = 'glossary'
                    JOIN {course_modules} cm ON (cm.module = m.id AND cm.instance = g.id)
                   WHERE ge.attachment <> '$empty' AND ge.attachment <> '1'";

        $count = $DB->count_records_sql("SELECT COUNT('x') $sqlfrom");

        $rs = $DB->get_recordset_sql("SELECT ge.id, ge.userid, ge.attachment, ge.glossaryid, ge.sourceglossaryid, g.course, cm.id AS cmid $sqlfrom ORDER BY g.course, g.id");
        if ($rs->valid()) {

            $pbar = new progress_bar('migrateglossaryfiles', 500, true);

            $i = 0;
            foreach ($rs as $entry) {
                $i++;
                upgrade_set_timeout(60); // set up timeout, may also abort execution
                $pbar->update($i, $count, "Migrating glossary entries - $i/$count.");

                $filepath = "$CFG->dataroot/$entry->course/$CFG->moddata/glossary/$entry->glossaryid/$entry->id/$entry->attachment";
                if ($entry->sourceglossaryid and !is_readable($filepath)) {
                    //eh - try the second possible location
                    $filepath = "$CFG->dataroot/$entry->course/$CFG->moddata/glossary/$entry->sourceglossaryid/$entry->id/$entry->attachment";

                }
                if (!is_readable($filepath)) {
                    //file missing??
                    echo $OUTPUT->notification("File not readable, skipping: $filepath");
                    $entry->attachment = '';
                    $DB->update_record('glossary_entries', $entry);
                    continue;
                }
                $context = get_context_instance(CONTEXT_MODULE, $entry->cmid);

                $filearea = 'attachment';
                $filename = clean_param($entry->attachment, PARAM_FILE);
                if ($filename === '') {
                    echo $OUTPUT->notification("Unsupported entry filename, skipping: ".$filepath);
                    $entry->attachment = '';
                    $DB->update_record('glossary_entries', $entry);
                    continue;
                }
                if (!$fs->file_exists($context->id, 'mod_glossary', $filearea, $entry->id, '/', $filename)) {
                    $file_record = array('contextid'=>$context->id, 'component'=>'mod_glossary', 'filearea'=>$filearea, 'itemid'=>$entry->id, 'filepath'=>'/', 'filename'=>$filename, 'userid'=>$entry->userid);
                    if ($fs->create_file_from_pathname($file_record, $filepath)) {
                        $entry->attachment = '1';
                        $DB->update_record('glossary_entries', $entry);
                        unlink($filepath);
                    }
                }

                // remove dirs if empty
                @rmdir("$CFG->dataroot/$entry->course/$CFG->moddata/glossary/$entry->glossaryid/$entry->id");
                @rmdir("$CFG->dataroot/$entry->course/$CFG->moddata/glossary/$entry->glossaryid");
                @rmdir("$CFG->dataroot/$entry->course/$CFG->moddata/glossary");
            }
        }
        $rs->close();

        upgrade_mod_savepoint(true, 2008081900, 'glossary');
    }

    if ($oldversion < 2009042000) {

    /// Rename field definitionformat on table glossary_entries to definitionformat
        $table = new xmldb_table('glossary_entries');
        $field = new xmldb_field('format', XMLDB_TYPE_INTEGER, '2', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'definition');

    /// Launch rename field definitionformat
        $dbman->rename_field($table, $field, 'definitionformat');

    /// glossary savepoint reached
        upgrade_mod_savepoint(true, 2009042000, 'glossary');
    }

    if ($oldversion < 2009042001) {

    /// Define field definitiontrust to be added to glossary_entries
        $table = new xmldb_table('glossary_entries');
        $field = new xmldb_field('definitiontrust', XMLDB_TYPE_INTEGER, '2', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'definitionformat');

    /// Launch add field definitiontrust
        $dbman->add_field($table, $field);

    /// glossary savepoint reached
        upgrade_mod_savepoint(true, 2009042001, 'glossary');
    }

    if ($oldversion < 2009042002) {

    /// Rename field format on table glossary_comments to NEWNAMEGOESHERE
        $table = new xmldb_table('glossary_comments');
        $field = new xmldb_field('format', XMLDB_TYPE_INTEGER, '2', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'entrycomment');

    /// Launch rename field format
        $dbman->rename_field($table, $field, 'entrycommentformat');

    /// glossary savepoint reached
        upgrade_mod_savepoint(true, 2009042002, 'glossary');
    }

    if ($oldversion < 2009042003) {

    /// Define field entrycommenttrust to be added to glossary_comments
        $table = new xmldb_table('glossary_comments');
        $field = new xmldb_field('entrycommenttrust', XMLDB_TYPE_INTEGER, '2', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'entrycommentformat');

    /// Conditionally launch add field entrycommenttrust
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }

    /// glossary savepoint reached
        upgrade_mod_savepoint(true, 2009042003, 'glossary');
    }

    if ($oldversion < 2009042004) {
        $trustmark = '#####TRUSTTEXT#####';
        $rs = $DB->get_recordset_sql("SELECT * FROM {glossary_entries} WHERE definition LIKE ?", array($trustmark.'%'));
        foreach ($rs as $entry) {
            if (strpos($entry->definition, $trustmark) !== 0) {
                // probably lowercase in some DBs
                continue;
            }
            $entry->definition      = str_replace($trustmark, '', $entry->definition);
            $entry->definitiontrust = 1;
            $DB->update_record('glossary_entries', $entry);
        }
        $rs->close();

    /// glossary savepoint reached
        upgrade_mod_savepoint(true, 2009042004, 'glossary');
    }

    if ($oldversion < 2009042005) {
        $trustmark = '#####TRUSTTEXT#####';
        $rs = $DB->get_recordset_sql("SELECT * FROM {glossary_comments} WHERE entrycomment LIKE ?", array($trustmark.'%'));
        foreach ($rs as $comment) {
            if (strpos($comment->entrycomment, $trustmark) !== 0) {
                // probably lowercase in some DBs
                continue;
            }
            $comment->entrycomment      = str_replace($trustmark, '', $comment->entrycomment);
            $comment->entrycommenttrust = 1;
            $DB->update_record('glossary_comments', $comment);
        }
        $rs->close();

    /// glossary savepoint reached
        upgrade_mod_savepoint(true, 2009042005, 'glossary');
    }

    if ($oldversion < 2009042006) {

    /// Define field introformat to be added to glossary
        $table = new xmldb_table('glossary');
        $field = new xmldb_field('introformat', XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'intro');

    /// Conditionally launch add field introformat
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }

        // conditionally migrate to html format in intro
        if ($CFG->texteditors !== 'textarea') {
            $rs = $DB->get_recordset('glossary', array('introformat'=>FORMAT_MOODLE), '', 'id,intro,introformat');
            foreach ($rs as $g) {
                $g->intro       = text_to_html($g->intro, false, false, true);
                $g->introformat = FORMAT_HTML;
                $DB->update_record('glossary', $g);
                upgrade_set_timeout();
            }
            $rs->close();
        }

    /// glossary savepoint reached
        upgrade_mod_savepoint(true, 2009042006, 'glossary');
    }
    if ($oldversion < 2009110800) {
        require_once($CFG->dirroot . '/comment/lib.php');
        upgrade_set_timeout(60*20);

    /// Define table glossary_comments to be dropped
        $table = new xmldb_table('glossary_comments');

    /// Conditionally launch drop table for glossary_comments
        if ($dbman->table_exists($table)) {
            $sql = "SELECT e.glossaryid AS glossaryid,
                           g.course AS courseid,
                           c.userid,
                           e.id AS itemid,
                           c.id AS old_id,
                           c.entrycomment AS commentcontent,
                           c.entrycommentformat AS format,
                           c.entrycommenttrust AS trust,
                           c.timemodified AS timemodified
                      FROM {glossary_comments} c, {glossary_entries} e, {glossary} g
                     WHERE c.entryid=e.id AND e.glossaryid=g.id
                  ORDER BY glossaryid, courseid";
            $lastglossaryid = null;
            $lastcourseid   = null;
            $modcontext     = null;

        /// move glossary comments to comments table
            $rs = $DB->get_recordset_sql($sql);
            foreach($rs as $res) {
                if ($res->glossaryid != $lastglossaryid || $res->courseid != $lastcourseid) {
                    $cm = get_coursemodule_from_instance('glossary', $res->glossaryid, $res->courseid);
                    if ($cm) {
                        $modcontext = get_context_instance(CONTEXT_MODULE, $cm->id);
                    }
                    $lastglossaryid = $res->glossaryid;
                    $lastcourseid   = $res->courseid;
                }
                $cmt = new stdClass();
                $cmt->contextid     = $modcontext->id;
                $cmt->commentarea   = 'glossary_entry';
                $cmt->itemid        = $res->itemid;
                $cmt->content       = $res->commentcontent;
                $cmt->format        = $res->format;
                $cmt->userid        = $res->userid;
                $cmt->timecreated    = $res->timemodified;
                $cmt_id = $DB->insert_record('comments', $cmt);
                if (!empty($cmt_id)) {
                    $DB->delete_records('glossary_comments', array('id'=>$res->old_id));
                }
            }
            $rs->close();
            $dbman->drop_table($table);
        }

    /// glossary savepoint reached
        upgrade_mod_savepoint(true, 2009110800, 'glossary');
    }

    if ($oldversion < 2010042800) {
        //migrate glossary_ratings to the central rating table
        $table = new xmldb_table('glossary_ratings');
        if ($dbman->table_exists($table)) {
            //glossary ratings only have a single time column so use it for both time created and modified
            $sql = "INSERT INTO {rating} (contextid, scaleid, itemid, rating, userid, timecreated, timemodified)

                    SELECT cxt.id, g.scale, r.entryid AS itemid, r.rating, r.userid, r.time AS timecreated, r.time AS timemodified
                      FROM {glossary_ratings} r
                      JOIN {glossary_entries} ge ON ge.id=r.entryid
                      JOIN {glossary} g ON g.id=ge.glossaryid
                      JOIN {course_modules} cm ON cm.instance=g.id
                      JOIN {context} cxt ON cxt.instanceid=cm.id
                      JOIN {modules} m ON m.id=cm.module
                     WHERE m.name = :modname AND cxt.contextlevel = :contextlevel";

            $params['modname'] = 'glossary';
            $params['contextlevel'] = CONTEXT_MODULE;

            $DB->execute($sql, $params);

            //now drop glossary_ratings
            $dbman->drop_table($table);
        }

        upgrade_mod_savepoint(true, 2010042800, 'glossary');
    }

    if ($oldversion < 2010111500) {
        // Delete orphaned glossary_entries not belonging to any glossary (MDL-25227)
        $sql = "DELETE FROM {glossary_entries}
                WHERE NOT EXISTS (
                    SELECT 'x' FROM {glossary} g
                    WHERE g.id = glossaryid)";
        $DB->execute($sql);

        upgrade_mod_savepoint(true, 2010111500, 'glossary');
    }

    if ($oldversion < 2010111501) {

        // Define field completionentries to be added to glossary
        $table = new xmldb_table('glossary');
        $field = new xmldb_field('completionentries', XMLDB_TYPE_INTEGER, '9', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'timemodified');

        // Conditionally launch add field completionentries
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }

        // glossary savepoint reached
        upgrade_mod_savepoint(true, 2010111501, 'glossary');
    }

    if ($oldversion < 2011052300) {
        // rating.component and rating.ratingarea have now been added as mandatory fields.
        // Presently you can only rate data entries so component = 'mod_glossary' and ratingarea = 'entry'
        // for all ratings with a glossary context.
        // We want to update all ratings that belong to a glossary context and don't already have a
        // component set.
        // This could take a while reset upgrade timeout to 5 min
        upgrade_set_timeout(60 * 20);
        $sql = "UPDATE {rating}
                SET component = 'mod_glossary', ratingarea = 'entry'
                WHERE contextid IN (
                    SELECT ctx.id
                      FROM {context} ctx
                      JOIN {course_modules} cm ON cm.id = ctx.instanceid
                      JOIN {modules} m ON m.id = cm.module
                     WHERE ctx.contextlevel = 70 AND
                           m.name = 'glossary'
                ) AND component = 'unknown'";
        $DB->execute($sql);

        upgrade_mod_savepoint(true, 2011052300, 'glossary');
    }

    // Moodle v2.1.0 release upgrade line
    // Put any upgrade step following this

    // Moodle v2.2.0 release upgrade line
    // Put any upgrade step following this

    return true;
}
Exemplo n.º 29
0
/**
 * Update all grades in gradebook.
 * @global object
 */
function forum_upgrade_grades() {
    global $DB;

    $sql = "SELECT COUNT('x')
              FROM {forum} f, {course_modules} cm, {modules} m
             WHERE m.name='forum' AND m.id=cm.module AND cm.instance=f.id";
    $count = $DB->count_records_sql($sql);

    $sql = "SELECT f.*, cm.idnumber AS cmidnumber, f.course AS courseid
              FROM {forum} f, {course_modules} cm, {modules} m
             WHERE m.name='forum' AND m.id=cm.module AND cm.instance=f.id";
    $rs = $DB->get_recordset_sql($sql);
    if ($rs->valid()) {
        $pbar = new progress_bar('forumupgradegrades', 500, true);
        $i=0;
        foreach ($rs as $forum) {
            $i++;
            upgrade_set_timeout(60*5); // set up timeout, may also abort execution
            forum_update_grades($forum, 0, false);
            $pbar->update($i, $count, "Updating Forum grades ($i/$count).");
        }
    }
    $rs->close();
}
Exemplo n.º 30
0
/**
 * Book module upgrade task
 *
 * @param int $oldversion the version we are upgrading from
 * @return bool always true
 */
function xmldb_book_upgrade($oldversion) {
    global $CFG, $DB;

    $dbman = $DB->get_manager();

    // Moodle v2.2.0 release upgrade line
    // Put any upgrade step following this

    // Moodle v2.3.0 release upgrade line
    // Put any upgrade step following this

    // Note: The next steps (up to 2012090408 included, are a "replay" of old upgrade steps,
    // because some sites updated to Moodle 2.3 didn't have the latest contrib mod_book
    // installed, so some required changes were missing.
    //
    // All the steps are run conditionally so sites upgraded from latest contrib mod_book or
    // new (2.3 and upwards) sites won't get affected.
    //
    // Warn: It will be safe to delete these steps once Moodle 2.5 (not 2.4!) is declared as minimum
    // requirement (environment.xml) in some future Moodle 2.x version. Never, never, before!
    //
    // See MDL-35297 and commit msg for more information.

    if ($oldversion < 2012090401) {
        // Rename field summary on table book to intro
        $table = new xmldb_table('book');
        $field = new xmldb_field('summary', XMLDB_TYPE_TEXT, null, null, null, null, null, 'name');

        // Launch rename field summary
        if ($dbman->field_exists($table, $field)) {
            $dbman->rename_field($table, $field, 'intro');
        }

        // book savepoint reached
        upgrade_mod_savepoint(true, 2012090401, 'book');
    }

    if ($oldversion < 2012090402) {
        // Define field introformat to be added to book
        $table = new xmldb_table('book');
        $field = new xmldb_field('introformat', XMLDB_TYPE_INTEGER, '4', null, XMLDB_NOTNULL, null, '0', 'intro');

        // Launch add field introformat
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
            // Conditionally migrate to html format in intro
            // Si está activo el htmleditor!!!!!
            if ($CFG->texteditors !== 'textarea') {
                $rs = $DB->get_recordset('book', array('introformat'=>FORMAT_MOODLE), '', 'id,intro,introformat');
                foreach ($rs as $b) {
                    $b->intro       = text_to_html($b->intro, false, false, true);
                    $b->introformat = FORMAT_HTML;
                    $DB->update_record('book', $b);
                    upgrade_set_timeout();
                }
                unset($b);
                $rs->close();
            }
        }

        // book savepoint reached
        upgrade_mod_savepoint(true, 2012090402, 'book');
    }

    if ($oldversion < 2012090403) {
        // Define field introformat to be added to book
        $table = new xmldb_table('book_chapters');
        $field = new xmldb_field('contentformat', XMLDB_TYPE_INTEGER, '4', null, XMLDB_NOTNULL, null, '0', 'content');

        // Launch add field introformat
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);

            $DB->set_field('book_chapters', 'contentformat', FORMAT_HTML, array());
        }

        // book savepoint reached
        upgrade_mod_savepoint(true, 2012090403, 'book');
    }

    if ($oldversion < 2012090404) {
        require_once("$CFG->dirroot/mod/book/db/upgradelib.php");

        $sqlfrom = "FROM {book} b
                    JOIN {modules} m ON m.name = 'book'
                    JOIN {course_modules} cm ON (cm.module = m.id AND cm.instance = b.id)";

        $count = $DB->count_records_sql("SELECT COUNT('x') $sqlfrom");

        if ($rs = $DB->get_recordset_sql("SELECT b.id, b.course, cm.id AS cmid $sqlfrom ORDER BY b.course, b.id")) {

            $pbar = new progress_bar('migratebookfiles', 500, true);

            $i = 0;
            foreach ($rs as $book) {
                $i++;
                upgrade_set_timeout(360); // set up timeout, may also abort execution
                $pbar->update($i, $count, "Migrating book files - $i/$count.");

                $context = context_module::instance($book->cmid);

                mod_book_migrate_moddata_dir_to_legacy($book, $context, '/');

                // remove dirs if empty
                @rmdir("$CFG->dataroot/$book->course/$CFG->moddata/book/$book->id/");
                @rmdir("$CFG->dataroot/$book->course/$CFG->moddata/book/");
                @rmdir("$CFG->dataroot/$book->course/$CFG->moddata/");
                @rmdir("$CFG->dataroot/$book->course/");
            }
            $rs->close();
        }

        // book savepoint reached
        upgrade_mod_savepoint(true, 2012090404, 'book');
    }

    if ($oldversion < 2012090405) {
        // Define field disableprinting to be dropped from book
        $table = new xmldb_table('book');
        $field = new xmldb_field('disableprinting');

        // Conditionally launch drop field disableprinting
        if ($dbman->field_exists($table, $field)) {
            $dbman->drop_field($table, $field);
        }

        // book savepoint reached
        upgrade_mod_savepoint(true, 2012090405, 'book');
    }

    if ($oldversion < 2012090406) {
        unset_config('book_tocwidth');

        // book savepoint reached
        upgrade_mod_savepoint(true, 2012090406, 'book');
    }

    if ($oldversion < 2012090407) {
        require_once("$CFG->dirroot/mod/book/db/upgradelib.php");

        mod_book_migrate_all_areas();

        upgrade_mod_savepoint(true, 2012090407, 'book');
    }

    if ($oldversion < 2012090408) {

        // Define field revision to be added to book
        $table = new xmldb_table('book');
        $field = new xmldb_field('revision', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0', 'customtitles');

        // Conditionally launch add field revision
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }

        // book savepoint reached
        upgrade_mod_savepoint(true, 2012090408, 'book');
    }
    // End of MDL-35297 "replayed" steps.

    // Moodle v2.4.0 release upgrade line
    // Put any upgrade step following this


    return true;
}