From 40e4cd435b81fd6164d2c64c3f0a2ad2eb2370f4 Mon Sep 17 00:00:00 2001 From: Petr Skoda Date: Tue, 6 Dec 2011 09:26:45 +0100 Subject: [PATCH] MDL-30610 remove outdated mod upgrade code --- mod/assignment/db/upgrade.php | 131 - mod/chat/db/upgrade.php | 77 - mod/choice/db/upgrade.php | 45 - mod/data/db/upgrade.php | 315 -- mod/feedback/db/upgrade.php | 324 -- mod/folder/db/install.php | 10 - mod/folder/db/upgrade.php | 2 - mod/folder/db/upgradelib.php | 107 - mod/forum/db/upgrade.php | 294 -- mod/glossary/db/upgrade.php | 326 -- mod/imscp/db/install.php | 11 - mod/imscp/db/upgrade.php | 2 - mod/imscp/db/upgradelib.php | 171 - mod/label/db/upgrade.php | 33 - mod/lesson/db/upgrade.php | 236 +- mod/lesson/db/upgradelib.php | 86 - mod/lti/db/upgrade.php | 13 - mod/page/db/install.php | 13 - mod/page/db/upgrade.php | 3 - mod/page/db/upgradelib.php | 147 - mod/quiz/db/upgrade.php | 1156 ------ mod/quiz/db/upgradelib.php | 94 - mod/resource/db/upgrade.php | 213 - mod/resource/db/upgradelib.php | 304 -- mod/scorm/db/upgrade.php | 569 --- mod/scorm/db/upgradelib.php | 109 - mod/survey/db/upgrade.php | 31 - mod/url/db/install.php | 17 - mod/url/db/upgrade.php | 16 - mod/url/db/upgradelib.php | 140 - mod/wiki/db/install.php | 2 - mod/wiki/db/migration/lib.php | 582 --- mod/wiki/db/migration/wiki/ewiki/ewiki.php | 3626 ----------------- .../plugins/moodle/moodle_rescue_html.php | 45 - mod/wiki/db/migration/wiki/ewikimoodlelib.php | 316 -- mod/wiki/db/upgrade.php | 331 -- mod/wiki/db/upgradelib.php | 338 -- mod/workshop/db/upgrade.php | 280 -- mod/workshop/db/upgradelib.php | 469 --- 39 files changed, 1 insertion(+), 10983 deletions(-) delete mode 100644 mod/folder/db/upgradelib.php delete mode 100644 mod/imscp/db/upgradelib.php delete mode 100644 mod/lesson/db/upgradelib.php delete mode 100644 mod/page/db/upgradelib.php delete mode 100644 mod/quiz/db/upgradelib.php delete mode 100644 mod/resource/db/upgradelib.php delete mode 100644 mod/scorm/db/upgradelib.php delete mode 100644 mod/url/db/upgradelib.php delete mode 100644 mod/wiki/db/migration/lib.php delete mode 100644 mod/wiki/db/migration/wiki/ewiki/ewiki.php delete mode 100644 mod/wiki/db/migration/wiki/ewiki/plugins/moodle/moodle_rescue_html.php delete mode 100644 mod/wiki/db/migration/wiki/ewikimoodlelib.php delete mode 100644 mod/wiki/db/upgradelib.php delete mode 100644 mod/workshop/db/upgradelib.php diff --git a/mod/assignment/db/upgrade.php b/mod/assignment/db/upgrade.php index 6340d8023ac..6608b6c2d88 100644 --- a/mod/assignment/db/upgrade.php +++ b/mod/assignment/db/upgrade.php @@ -25,137 +25,6 @@ function xmldb_assignment_upgrade($oldversion) { $dbman = $DB->get_manager(); -//===== 1.9.0 upgrade line ======// - - if ($oldversion < 2007101511) { - // change grade typo to text if no grades MDL-13920 - require_once $CFG->dirroot.'/mod/assignment/lib.php'; - assignment_upgrade_grades(); - upgrade_mod_savepoint(true, 2007101511, 'assignment'); - } - - if ($oldversion < 2008081900) { - - ///////////////////////////////////// - /// new file storage upgrade code /// - ///////////////////////////////////// - - $fs = get_file_storage(); - - $sqlfrom = "FROM {assignment_submissions} s - JOIN {assignment} a ON a.id = s.assignment - JOIN {modules} m ON m.name = 'assignment' - JOIN {course_modules} cm ON (cm.module = m.id AND cm.instance = a.id)"; - - $count = $DB->count_records_sql("SELECT COUNT('x') $sqlfrom"); - - $rs = $DB->get_recordset_sql("SELECT s.id, s.userid, s.teacher, s.assignment, a.course, cm.id AS cmid $sqlfrom ORDER BY a.course, s.assignment"); - - if ($rs->valid()) { - $pbar = new progress_bar('migrateassignmentfiles', 500, true); - $i = 0; - foreach ($rs as $submission) { - $i++; - upgrade_set_timeout(180); // set up timeout, may also abort execution - $pbar->update($i, $count, "Migrating assignment submissions - $i/$count."); - - $basepath = "$CFG->dataroot/$submission->course/$CFG->moddata/assignment/$submission->assignment/$submission->userid/"; - if (!file_exists($basepath)) { - //no files - continue; - } - $context = get_context_instance(CONTEXT_MODULE, $submission->cmid); - - // migrate submitted files first - $path = $basepath; - $items = new DirectoryIterator($path); - foreach ($items as $item) { - if (!$item->isFile()) { - continue; - } - if (!$item->isReadable()) { - echo $OUTPUT->notification(" File not readable, skipping: ".$path.$item->getFilename()); - continue; - } - $filename = clean_param($item->getFilename(), PARAM_FILE); - if ($filename === '') { - continue; - } - if (!$fs->file_exists($context->id, 'mod_assignment', 'submission', $submission->id, '/', $filename)) { - $file_record = array('contextid'=>$context->id, 'component'=>'mod_assignment', 'filearea'=>'submission', 'itemid'=>$submission->id, 'filepath'=>'/', 'filename'=>$filename, 'userid'=>$submission->userid); - if ($fs->create_file_from_pathname($file_record, $path.$item->getFilename())) { - unlink($path.$item->getFilename()); - } - } - } - unset($items); //release file handles - - // migrate teacher response files for "upload" subtype, unfortunately we do not - $path = $basepath.'responses/'; - if (file_exists($path)) { - $items = new DirectoryIterator($path); - foreach ($items as $item) { - if (!$item->isFile()) { - continue; - } - $filename = clean_param($item->getFilename(), PARAM_FILE); - if ($filename === '') { - continue; - } - if (!$fs->file_exists($context->id, 'mod_assignment', 'response', $submission->id, '/', $filename)) { - $file_record = array('contextid'=>$context->id, 'component'=>'mod_assignment', 'filearea'=>'response', 'itemid'=>$submission->id, 'filepath'=>'/', 'filename'=>$filename, - 'timecreated'=>$item->getCTime(), 'timemodified'=>$item->getMTime()); - if ($submission->teacher) { - $file_record['userid'] = $submission->teacher; - } - if ($fs->create_file_from_pathname($file_record, $path.$item->getFilename())) { - unlink($path.$item->getFilename()); - } - } - } - unset($items); //release file handles - @rmdir("$CFG->dataroot/$submission->course/$CFG->moddata/assignment/$submission->assignment/$submission->userid/responses"); - } - - // remove dirs if empty - @rmdir("$CFG->dataroot/$submission->course/$CFG->moddata/assignment/$submission->assignment/$submission->userid"); - @rmdir("$CFG->dataroot/$submission->course/$CFG->moddata/assignment/$submission->assignment"); - @rmdir("$CFG->dataroot/$submission->course/$CFG->moddata/assignment"); - } - } - $rs->close(); - - upgrade_mod_savepoint(true, 2008081900, 'assignment'); - } - - if ($oldversion < 2009042000) { - - /// Rename field description on table assignment to intro - $table = new xmldb_table('assignment'); - $field = new xmldb_field('description', XMLDB_TYPE_TEXT, 'small', null, XMLDB_NOTNULL, null, null, 'name'); - - /// Launch rename field description - $dbman->rename_field($table, $field, 'intro'); - - /// assignment savepoint reached - upgrade_mod_savepoint(true, 2009042000, 'assignment'); - } - - if ($oldversion < 2009042001) { - - /// Rename field format on table assignment to introformat - $table = new xmldb_table('assignment'); - $field = new xmldb_field('format', XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'intro'); - - /// Launch rename field format - $dbman->rename_field($table, $field, 'introformat'); - - /// assignment savepoint reached - upgrade_mod_savepoint(true, 2009042001, 'assignment'); - } - - // 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 diff --git a/mod/chat/db/upgrade.php b/mod/chat/db/upgrade.php index d1c8ac00ffa..2b9ad1d76c1 100644 --- a/mod/chat/db/upgrade.php +++ b/mod/chat/db/upgrade.php @@ -25,83 +25,6 @@ function xmldb_chat_upgrade($oldversion) { $dbman = $DB->get_manager(); - //===== 1.9.0 upgrade line ======// - - if ($oldversion < 2010050100) { - - /// Changing precision of field ip on table chat_users to (45) - $table = new xmldb_table('chat_users'); - $field = new xmldb_field('ip', XMLDB_TYPE_CHAR, '45', null, XMLDB_NOTNULL, null, null, 'version'); - - /// Launch change of precision for field ip - $dbman->change_field_precision($table, $field); - - /// chat savepoint reached - upgrade_mod_savepoint(true, 2010050100, 'chat'); - } - - if ($oldversion < 2010050101) { - - /// Define field introformat to be added to chat - $table = new xmldb_table('chat'); - $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('chat', array('introformat'=>FORMAT_MOODLE), '', 'id,intro,introformat'); - foreach ($rs as $ch) { - $ch->intro = text_to_html($ch->intro, false, false, true); - $ch->introformat = FORMAT_HTML; - $DB->update_record('chat', $ch); - upgrade_set_timeout(); - } - $rs->close(); - } - - /// chat savepoint reached - upgrade_mod_savepoint(true, 2010050101, 'chat'); - } - - /// Creating chat_messages_current to hold latest chat messages - if ($oldversion < 2010050102) { - - /// Define table chat_messages_current to be created - $table = new xmldb_table('chat_messages_current'); - - /// Adding fields to table chat_messages_current - $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); - $table->add_field('chatid', 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('groupid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); - $table->add_field('system', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); - $table->add_field('message', XMLDB_TYPE_TEXT, 'small', null, XMLDB_NOTNULL, null, null); - $table->add_field('timestamp', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); - - /// Adding keys to table chat_messages_current - $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); - $table->add_key('chatid', XMLDB_KEY_FOREIGN, array('chatid'), 'chat', array('id')); - - /// Adding indexes to table chat_messages_current - $table->add_index('userid', XMLDB_INDEX_NOTUNIQUE, array('userid')); - $table->add_index('groupid', XMLDB_INDEX_NOTUNIQUE, array('groupid')); - $table->add_index('timestamp-chatid', XMLDB_INDEX_NOTUNIQUE, array('timestamp', 'chatid')); - - /// create table for chat_messages_current - if (!$dbman->table_exists($table)) { - $dbman->create_table($table); - } - - /// chat savepoint reached - upgrade_mod_savepoint(true, 2010050102, 'chat'); - } - - // 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 diff --git a/mod/choice/db/upgrade.php b/mod/choice/db/upgrade.php index d75dc24a2d7..f86bbe4f4a3 100644 --- a/mod/choice/db/upgrade.php +++ b/mod/choice/db/upgrade.php @@ -25,51 +25,6 @@ function xmldb_choice_upgrade($oldversion) { $dbman = $DB->get_manager(); -//===== 1.9.0 upgrade line ======// - - if ($oldversion < 2009042000) { - - /// Rename field text on table choice to text - $table = new xmldb_table('choice'); - $field = new xmldb_field('text', XMLDB_TYPE_TEXT, 'small', null, XMLDB_NOTNULL, null, null, 'name'); - - /// Launch rename field text - $dbman->rename_field($table, $field, 'intro'); - - /// choice savepoint reached - upgrade_mod_savepoint(true, 2009042000, 'choice'); - } - - if ($oldversion < 2009042001) { - - /// Rename field format on table choice to format - $table = new xmldb_table('choice'); - $field = new xmldb_field('format', XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'intro'); - - /// Launch rename field format - $dbman->rename_field($table, $field, 'introformat'); - - /// choice savepoint reached - upgrade_mod_savepoint(true, 2009042001, 'choice'); - } - - if ($oldversion < 2010101300) { - - // Define field completionsubmit to be added to choice - $table = new xmldb_table('choice'); - $field = new xmldb_field('completionsubmit', XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, '0', 'timemodified'); - - // Conditionally launch add field completionsubmit - if (!$dbman->field_exists($table, $field)) { - $dbman->add_field($table, $field); - } - - // choice savepoint reached - upgrade_mod_savepoint(true, 2010101300, 'choice'); - } - - // 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 diff --git a/mod/data/db/upgrade.php b/mod/data/db/upgrade.php index 8983a9ba67d..a84c88337dc 100644 --- a/mod/data/db/upgrade.php +++ b/mod/data/db/upgrade.php @@ -25,321 +25,6 @@ function xmldb_data_upgrade($oldversion) { $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.")
"; - } - //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 diff --git a/mod/feedback/db/upgrade.php b/mod/feedback/db/upgrade.php index 73b4520502d..c4ededd907b 100644 --- a/mod/feedback/db/upgrade.php +++ b/mod/feedback/db/upgrade.php @@ -39,330 +39,6 @@ function xmldb_feedback_upgrade($oldversion) { $dbman = $DB->get_manager(); - if ($oldversion < 2007012310) { - - //create a new table feedback_completedtmp and the field-definition - $table = new xmldb_table('feedback_completedtmp'); - - $field = new xmldb_field('id'); - $field->set_attributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, - XMLDB_NOTNULL, true, null, null); - $table->addField($field); - - $field = new xmldb_field('feedback'); - $field->set_attributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, - XMLDB_NOTNULL, false, '0', null); - $table->addField($field); - - $field = new xmldb_field('userid'); - $field->set_attributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, - XMLDB_NOTNULL, false, '0', null); - $table->addField($field); - - $field = new xmldb_field('guestid'); - $field->set_attributes(XMLDB_TYPE_CHAR, '255', null, null, false, '', null); - $table->addField($field); - - $field = new xmldb_field('timemodified'); - $field->set_attributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, - XMLDB_NOTNULL, false, '0', null); - $table->addField($field); - - $key = new xmldb_key('PRIMARY'); - $key->set_attributes(XMLDB_KEY_PRIMARY, array('id')); - $table->addKey($key); - - $key = new xmldb_key('feedback'); - $key->set_attributes(XMLDB_KEY_FOREIGN, array('feedback'), 'feedback', 'id'); - $table->addKey($key); - - $dbman->create_table($table); - //////////////////////////////////////////////////////////// - //////////////////////////////////////////////////////////// - //create a new table feedback_valuetmp and the field-definition - $table = new xmldb_table('feedback_valuetmp'); - - $field = new xmldb_field('id'); - $field->set_attributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, - XMLDB_NOTNULL, true, null, null); - $table->addField($field); - - $field = new xmldb_field('course_id'); - $field->set_attributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, - XMLDB_NOTNULL, false, '0', null); - $table->addField($field); - - $field = new xmldb_field('item'); - $field->set_attributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, - XMLDB_NOTNULL, false, '0', null); - $table->addField($field); - - $field = new xmldb_field('completed'); - $field->set_attributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, - XMLDB_NOTNULL, false, '0', null); - $table->addField($field); - - $field = new xmldb_field('tmp_completed'); - $field->set_attributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, - XMLDB_NOTNULL, false, '0', null); - $table->addField($field); - - $field = new xmldb_field('value'); - $field->set_attributes(XMLDB_TYPE_TEXT, null, null, null, false, '', null); - $table->addField($field); - - $key = new xmldb_key('PRIMARY'); - $key->set_attributes(XMLDB_KEY_PRIMARY, array('id')); - $table->addKey($key); - - $key = new xmldb_key('feedback'); - $key->set_attributes(XMLDB_KEY_FOREIGN, array('item'), 'feedback_item', 'id'); - $table->addKey($key); - - $dbman->create_table($table); - //////////////////////////////////////////////////////////// - upgrade_mod_savepoint(true, 2007012310, 'feedback'); - } - - if ($oldversion < 2007050504) { - - /// Define field random_response to be added to feedback_completed - $table = new xmldb_table('feedback_completed'); - $field = new xmldb_field('random_response', XMLDB_TYPE_INTEGER, '10', - XMLDB_UNSIGNED, XMLDB_NOTNULL, false, '0', null); - /// Launch add field1 - $dbman->add_field($table, $field); - - /// Define field anonymous_response to be added to feedback_completed - $table = new xmldb_table('feedback_completed'); - $field = new xmldb_field('anonymous_response', XMLDB_TYPE_INTEGER, '1', - XMLDB_UNSIGNED, XMLDB_NOTNULL, false, '1', null); - /// Launch add field2 - $dbman->add_field($table, $field); - - /// Define field random_response to be added to feedback_completed - $table = new xmldb_table('feedback_completedtmp'); - $field = new xmldb_field('random_response', XMLDB_TYPE_INTEGER, '10', - XMLDB_UNSIGNED, XMLDB_NOTNULL, false, '0', null); - /// Launch add field1 - $dbman->add_field($table, $field); - - /// Define field anonymous_response to be added to feedback_completed - $table = new xmldb_table('feedback_completedtmp'); - $field = new xmldb_field('anonymous_response', XMLDB_TYPE_INTEGER, '1', - XMLDB_UNSIGNED, XMLDB_NOTNULL, false, '1', null); - /// Launch add field2 - $dbman->add_field($table, $field); - - //////////////////////////////////////////////////////////// - upgrade_mod_savepoint(true, 2007050504, 'feedback'); - } - - if ($oldversion < 2007102600) { - // public is a reserved word on Oracle - - $table = new xmldb_table('feedback_template'); - $field = new xmldb_field('ispublic', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, - XMLDB_NOTNULL, false, '1', null); - if (!$dbman->field_exists($table, $field)) { - $dbman->add_field($table, $field); - } - upgrade_mod_savepoint(true, 2007102600, 'feedback'); - } - - if ($oldversion < 2008042400) { //New version in version.php - if ($all_nonanonymous_feedbacks = $DB->get_records('feedback', array('anonymous'=>2))) { - $update_sql = 'UPDATE {feedback_completed} - SET anonymous_response = 2 - WHERE feedback = '; - foreach ($all_nonanonymous_feedbacks as $fb) { - $DB->execute($update_sql.$fb->id); - } - } - upgrade_mod_savepoint(true, 2008042400, 'feedback'); - } - - if ($oldversion < 2008042401) { //New version in version.php - $concat_radio = $DB->sql_concat("'r>>>>>'", 'presentation'); - $concat_check = $DB->sql_concat("'c>>>>>'", 'presentation'); - $concat_dropdown = $DB->sql_concat("'d>>>>>'", 'presentation'); - - $update_sql1 = "UPDATE {feedback_item} - SET presentation = ".$concat_radio." - WHERE typ IN('radio','radiorated')"; - - $update_sql2 = "UPDATE {feedback_item} - SET presentation = ".$concat_dropdown." - WHERE typ IN('dropdown','dropdownrated')"; - - $update_sql3 = "UPDATE {feedback_item} - SET presentation = ".$concat_check." - WHERE typ = 'check'"; - - $DB->execute($update_sql1); - $DB->execute($update_sql2); - $DB->execute($update_sql3); - - $update_sql1 = "UPDATE {feedback_item} - SET typ = 'multichoice' - WHERE typ IN('radio','check','dropdown')"; - - $update_sql2 = "UPDATE {feedback_item} - SET typ = 'multichoicerated' - WHERE typ IN('radiorated','dropdownrated')"; - - $DB->execute($update_sql1); - $DB->execute($update_sql2); - - upgrade_mod_savepoint(true, 2008042401, 'feedback'); - } - - if ($oldversion < 2008042900) { - /// Define field autonumbering to be added to feedback - $table = new xmldb_table('feedback'); - $field = new xmldb_field('autonumbering', XMLDB_TYPE_INTEGER, '1', - XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '1', 'multiple_submit'); - /// Launch add field2 - $dbman->add_field($table, $field); - - upgrade_mod_savepoint(true, 2008042900, 'feedback'); - } - - if ($oldversion < 2008050104) { - /// Define field site_after_submit to be added to feedback - $table = new xmldb_table('feedback'); - $field = new xmldb_field('site_after_submit', XMLDB_TYPE_CHAR, '255', - null, null, false, '', 'autonumbering'); - /// Launch add field2 - $dbman->add_field($table, $field); - - upgrade_mod_savepoint(true, 2008050104, 'feedback'); - } - - if ($oldversion < 2008050105) { - //field count is not more needed - $table = new xmldb_table('feedback_tracking'); - $field = new xmldb_field('count'); - $dbman->drop_field($table, $field); - - upgrade_mod_savepoint(true, 2008050105, 'feedback'); - } - - if ($oldversion < 2008073002) { - $update_sql = "UPDATE {feedback_item} - SET presentation = '-|-' - WHERE " . $DB->sql_compare_text('presentation') . " = '0|0' AND - typ = 'numeric'"; - - $DB->execute($update_sql); - - upgrade_mod_savepoint(true, 2008073002, 'feedback'); - } - - if ($oldversion < 2009031301) { - /// Define field label to be added to feedback_item - $table = new xmldb_table('feedback_item'); - $field = new xmldb_field('label', XMLDB_TYPE_CHAR, '255', null, null, false, '', 'name'); - /// Launch add field2 - $dbman->add_field($table, $field); - - upgrade_mod_savepoint(true, 2009031301, 'feedback'); - } - - if ($oldversion < 2009042000) { - - /// Rename field summary on table feedback to intro - $table = new xmldb_table('feedback'); - $field = new xmldb_field('summary', XMLDB_TYPE_TEXT, 'small', null, - XMLDB_NOTNULL, null, null, 'name'); - - /// Launch rename field summary - $dbman->rename_field($table, $field, 'intro'); - - /// feedback savepoint reached - upgrade_mod_savepoint(true, 2009042000, 'feedback'); - } - - if ($oldversion < 2009042001) { - - /// Define field introformat to be added to feedback - $table = new xmldb_table('feedback'); - $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); - - /// feedback savepoint reached - upgrade_mod_savepoint(true, 2009042001, 'feedback'); - } - - if ($oldversion < 2009112000) { - /// Define field page_after_submitformat to be added to feedback - $table = new xmldb_table('feedback'); - $field = new xmldb_field('page_after_submitformat', XMLDB_TYPE_INTEGER, '2', - XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'page_after_submit'); - - if (!$dbman->field_exists($table, $field)) { - // Launch add field page_after_submitformat - $dbman->add_field($table, $field); - } - - // feedback savepoint reached - upgrade_mod_savepoint(true, 2009112000, 'feedback'); - } - - if ($oldversion < 2010051101) { - /// Define field options to be added to feedback_item - $table = new xmldb_table('feedback_item'); - $field = new xmldb_field('options', XMLDB_TYPE_CHAR, '255', - null, null, false, '', 'required'); - /// Launch add field - $dbman->add_field($table, $field); - - upgrade_mod_savepoint(true, 2010051101, 'feedback'); - } - - if ($oldversion < 2010051600) { - /// Define field options to be added to feedback_item - $table = new xmldb_table('feedback_item'); - $field = new xmldb_field('dependitem', XMLDB_TYPE_INTEGER, '10', - XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'required'); - /// Launch add field - $dbman->add_field($table, $field); - - upgrade_mod_savepoint(true, 2010051600, 'feedback'); - } - - if ($oldversion < 2010051601) { - /// Define field options to be added to feedback_item - $table = new xmldb_table('feedback_item'); - $field = new xmldb_field('dependvalue', XMLDB_TYPE_CHAR, '255', - null, null, false, '', 'dependitem'); - /// Launch add field - $dbman->add_field($table, $field); - - upgrade_mod_savepoint(true, 2010051601, 'feedback'); - } - - if ($oldversion < 2010102300) { - - // Define field completionsubmit to be added to feedback - $table = new xmldb_table('feedback'); - $field = new xmldb_field('completionsubmit', XMLDB_TYPE_INTEGER, '1', - null, XMLDB_NOTNULL, null, '0', 'timemodified'); - - // Conditionally launch add field completionsubmit - if (!$dbman->field_exists($table, $field)) { - $dbman->add_field($table, $field); - } - - // feedback savepoint reached - upgrade_mod_savepoint(true, 2010102300, 'feedback'); - } - - // 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 diff --git a/mod/folder/db/install.php b/mod/folder/db/install.php index bb12b6b35ee..19842e94756 100644 --- a/mod/folder/db/install.php +++ b/mod/folder/db/install.php @@ -34,14 +34,4 @@ defined('MOODLE_INTERNAL') || die(); function xmldb_folder_install() { global $CFG; - // Upgrade from old resource module type if needed - require_once("$CFG->dirroot/mod/folder/db/upgradelib.php"); - folder_20_migrate(); } - -function xmldb_folder_install_recovery() { - global $CFG; - - require_once("$CFG->dirroot/mod/folder/db/upgradelib.php"); - folder_20_migrate(); -} \ No newline at end of file diff --git a/mod/folder/db/upgrade.php b/mod/folder/db/upgrade.php index 8e33d6a949c..7a2b6e2734f 100644 --- a/mod/folder/db/upgrade.php +++ b/mod/folder/db/upgrade.php @@ -51,8 +51,6 @@ function xmldb_folder_upgrade($oldversion) { $dbman = $DB->get_manager(); - // 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 diff --git a/mod/folder/db/upgradelib.php b/mod/folder/db/upgradelib.php deleted file mode 100644 index 0be56e1c70e..00000000000 --- a/mod/folder/db/upgradelib.php +++ /dev/null @@ -1,107 +0,0 @@ -. - -/** - * Folder module upgrade related helper functions - * - * @package mod - * @subpackage folder - * @copyright 2009 Petr Skoda {@link http://skodak.org} - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ - -defined('MOODLE_INTERNAL') || die(); - -/** - * Migrate folder module data from 1.9 resource_old table to new older table - * @return void - */ -function folder_20_migrate() { - global $CFG, $DB; - require_once("$CFG->libdir/filelib.php"); - require_once("$CFG->dirroot/course/lib.php"); - - if (!file_exists("$CFG->dirroot/mod/resource/db/upgradelib.php")) { - // bad luck, somebody deleted resource module - return; - } - - require_once("$CFG->dirroot/mod/resource/db/upgradelib.php"); - - // create resource_old table and copy resource table there if needed - if (!resource_20_prepare_migration()) { - // no modules or fresh install - return; - } - - $candidates = $DB->get_recordset('resource_old', array('type'=>'directory', 'migrated'=>0)); - - if (!$candidates->valid()) { - $candidates->close(); // Not going to iterate (but exit), close rs - return; - } - - $fs = get_file_storage(); - - foreach ($candidates as $candidate) { - upgrade_set_timeout(); - - $directory = '/'.trim($candidate->reference, '/').'/'; - $directory = str_replace('//', '/', $directory); - - if ($CFG->texteditors !== 'textarea') { - $intro = text_to_html($candidate->intro, false, false, true); - $introformat = FORMAT_HTML; - } else { - $intro = $candidate->intro; - $introformat = FORMAT_MOODLE; - } - - $folder = new stdClass(); - $folder->course = $candidate->course; - $folder->name = $candidate->name; - $folder->intro = $intro; - $folder->introformat = $introformat; - $folder->revision = 1; - $folder->timemodified = time(); - - if (!$folder = resource_migrate_to_module('folder', $candidate, $folder)) { - continue; - } - - // copy files in given directory, skip moddata and backups! - $context = get_context_instance(CONTEXT_MODULE, $candidate->cmid); - $coursecontext = get_context_instance(CONTEXT_COURSE, $candidate->course); - $files = $fs->get_directory_files($coursecontext->id, 'course', 'legacy', 0, $directory, true, true); - $file_record = array('contextid'=>$context->id, 'component'=>'mod_folder', 'filearea'=>'content', 'itemid'=>0); - foreach ($files as $file) { - $path = $file->get_filepath(); - if (stripos($path, '/backupdata/') === 0 or stripos($path, '/moddata/') === 0) { - // do not publish protected data! - continue; - } - $relpath = substr($path, strlen($directory) - 1); // keep only subfolder paths - $file_record['filepath'] = $relpath; - $fs->create_file_from_storedfile($file_record, $file); - } - } - - $candidates->close(); - - // clear all course modinfo caches - rebuild_course_cache(0, true); -} diff --git a/mod/forum/db/upgrade.php b/mod/forum/db/upgrade.php index 853a195c5b4..d493b2b77d3 100644 --- a/mod/forum/db/upgrade.php +++ b/mod/forum/db/upgrade.php @@ -46,300 +46,6 @@ function xmldb_forum_upgrade($oldversion) { $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 - JOIN {forum_discussions} d ON d.id = p.discussion - JOIN {forum} f ON f.id = d.forum - JOIN {modules} m ON m.name = 'forum' - JOIN {course_modules} cm ON (cm.module = m.id AND cm.instance = f.id) - 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) - - SELECT cxt.id, f.scale, r.post AS itemid, r.rating, r.userid, r.time AS timecreated, r.time AS timemodified - FROM {forum_ratings} r - JOIN {forum_posts} p ON p.id=r.post - JOIN {forum_discussions} d ON d.id=p.discussion - JOIN {forum} f ON f.id=d.forum - JOIN {course_modules} cm ON cm.instance=f.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'] = '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'); - } - - if ($oldversion < 2011052300) { - // rating.component and rating.ratingarea have now been added as mandatory fields. - // Presently you can only rate forum posts so component = 'mod_forum' and ratingarea = 'post' - // for all ratings with a forum context. - // We want to update all ratings that belong to a forum 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_forum', ratingarea = 'post' - 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 = 'forum' - ) AND component = 'unknown'"; - $DB->execute($sql); - - upgrade_mod_savepoint(true, 2011052300, 'forum'); - } - - // 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 diff --git a/mod/glossary/db/upgrade.php b/mod/glossary/db/upgrade.php index f70627f84f6..4eef079f3fd 100644 --- a/mod/glossary/db/upgrade.php +++ b/mod/glossary/db/upgrade.php @@ -25,332 +25,6 @@ function xmldb_glossary_upgrade($oldversion) { $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 diff --git a/mod/imscp/db/install.php b/mod/imscp/db/install.php index c7a23ba21f9..a99e8946233 100644 --- a/mod/imscp/db/install.php +++ b/mod/imscp/db/install.php @@ -34,15 +34,4 @@ defined('MOODLE_INTERNAL') || die(); function xmldb_imscp_install() { global $CFG; - // Upgrade from old resource module type if needed - require_once("$CFG->dirroot/mod/imscp/db/upgradelib.php"); - imscp_20_migrate(); -} - -function xmldb_imscp_install_recovery() { - global $CFG; - - // Upgrade from old resource module type if needed - require_once("$CFG->dirroot/mod/imscp/db/upgradelib.php"); - imscp_20_migrate(); } diff --git a/mod/imscp/db/upgrade.php b/mod/imscp/db/upgrade.php index 06a695d9727..2b027f7f2b2 100644 --- a/mod/imscp/db/upgrade.php +++ b/mod/imscp/db/upgrade.php @@ -31,8 +31,6 @@ function xmldb_imscp_upgrade($oldversion) { $dbman = $DB->get_manager(); - // 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 diff --git a/mod/imscp/db/upgradelib.php b/mod/imscp/db/upgradelib.php deleted file mode 100644 index 5138318e6e7..00000000000 --- a/mod/imscp/db/upgradelib.php +++ /dev/null @@ -1,171 +0,0 @@ -. - -/** - * IMS CP module upgrade related helper functions - * - * @package mod - * @subpackage imscp - * @copyright 2009 Petr Skoda {@link http://skodak.org} - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ - -defined('MOODLE_INTERNAL') || die(); - -/** - * Migrate imscp module data from 1.9 resource_old table to new imscp table - * @return void - */ -function imscp_20_migrate() { - global $CFG, $DB, $OUTPUT; - require_once("$CFG->libdir/filelib.php"); - require_once("$CFG->dirroot/course/lib.php"); - require_once("$CFG->dirroot/mod/imscp/locallib.php"); - - if (!file_exists("$CFG->dirroot/mod/resource/db/upgradelib.php")) { - // bad luck, somebody deleted resource module - return; - } - - require_once("$CFG->dirroot/mod/resource/db/upgradelib.php"); - - // create resource_old table and copy resource table there if needed - if (!resource_20_prepare_migration()) { - // no modules or fresh install - return; - } - - $candidates = $DB->get_recordset('resource_old', array('type'=>'ims', 'migrated'=>0)); - if (!$candidates->valid()) { - $candidates->close(); // Not going to iterate (but exit), close rs - return; - } - - $fs = get_file_storage(); - - foreach ($candidates as $candidate) { - upgrade_set_timeout(60); - - if ($CFG->texteditors !== 'textarea') { - $intro = text_to_html($candidate->intro, false, false, true); - $introformat = FORMAT_HTML; - } else { - $intro = $candidate->intro; - $introformat = FORMAT_MOODLE; - } - - $imscp = new stdClass(); - $imscp->course = $candidate->course; - $imscp->name = $candidate->name; - $imscp->intro = $intro; - $imscp->introformat = $introformat; - $imscp->revision = 1; - $imscp->keepold = 1; - $imscp->timemodified = time(); - - if (!$imscp = resource_migrate_to_module('imscp', $candidate, $imscp)) { - continue; - } - - $context = get_context_instance(CONTEXT_MODULE, $candidate->cmid); - $root = "$CFG->dataroot/$candidate->course/$CFG->moddata/resource/$candidate->oldid"; - - // migrate package backup file - if ($candidate->reference) { - $package = basename($candidate->reference); - $fullpath = $root.'/'.$package; - if (file_exists($fullpath)) { - $file_record = array('contextid' => $context->id, - 'component' => 'mod_imscp', - 'filearea' => 'backup', - 'itemid' => 1, - 'filepath' => '/', - 'filename' => $package); - $fs->create_file_from_pathname($file_record, $fullpath); - } - } - - // migrate extracted package data - $files = imsc_migrate_get_old_files($root, ''); - if (empty($files)) { - // if ims package doesn't exist, continue loop - echo $OUTPUT->notification("IMS package data cannot be found, failed migrating activity: \"$candidate->name\", please fix it manually"); - continue; - } - - $file_record = array('contextid'=>$context->id, 'component'=>'mod_imscp', 'filearea'=>'content', 'itemid'=>1); - $error = false; - foreach ($files as $relname=>$fullpath) { - $parts = explode('/', $relname); - $file_record['filename'] = array_pop($parts); - $parts[] = ''; // keep trailing slash - $file_record['filepath'] = implode('/', $parts); - - try { - $fs->create_file_from_pathname($file_record, $fullpath); - } catch (Exception $e) { - //continue on error, we can not recover anyway - $error = true; - echo $OUTPUT->notification("IMSCP: failed migrating file: $relname"); - } - } - unset($files); - - // parse manifest - $structure = imscp_parse_structure($imscp, $context); - $imscp->structure = is_array($structure) ? serialize($structure) : null; - $DB->update_record('imscp', $imscp); - - // remove old moddata dir only if no error and manifest ok - if (!$error and is_array($structure)) { - fulldelete($root); - } - } - $candidates->close(); - - // clear all course modinfo caches - rebuild_course_cache(0, true); -} - -/** - * Private function returning all extracted IMS content package file - */ -function imsc_migrate_get_old_files($path, $relative) { - global $OUTPUT; - $result = array(); - if (!file_exists($path)) { - echo $OUTPUT->notification("File path doesn't exist: $path
Please fix it manually."); - return array(); - } - $items = new DirectoryIterator($path); - foreach ($items as $item) { - if ($item->isDot() or $item->isLink()) { - // symbolic links could create infinite loops or cause unintended file migration, sorry - continue; - } - $pathname = $item->getPathname(); - $relname = $relative.'/'.$item->getFilename(); - if ($item->isFile()) { - $result[$relname] = $pathname; - } else if ($item->isDir()) { - $result = array_merge($result, imsc_migrate_get_old_files($pathname, $relname)); - } - unset($item); - } - unset($items); - return $result; -} diff --git a/mod/label/db/upgrade.php b/mod/label/db/upgrade.php index a8d49095835..0511d0fbf5d 100644 --- a/mod/label/db/upgrade.php +++ b/mod/label/db/upgrade.php @@ -51,39 +51,6 @@ function xmldb_label_upgrade($oldversion) { $dbman = $DB->get_manager(); -//===== 1.9.0 upgrade line ======// - - if ($oldversion < 2009042200) { - - /// Rename field content on table label to intro - $table = new xmldb_table('label'); - $field = new xmldb_field('content', XMLDB_TYPE_TEXT, 'small', null, XMLDB_NOTNULL, null, null, 'name'); - - /// Launch rename field content - $dbman->rename_field($table, $field, 'intro'); - - /// label savepoint reached - upgrade_mod_savepoint(true, 2009042200, 'label'); - } - - if ($oldversion < 2009042201) { - - /// Define field introformat to be added to label - $table = new xmldb_table('label'); - $field = new xmldb_field('introformat', XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, null, null, '0', 'intro'); - - /// Launch add field introformat - $dbman->add_field($table, $field); - - // all existing lables in 1.9 are in HTML format - $DB->set_field('label', 'introformat', FORMAT_HTML, array()); - - /// label savepoint reached - upgrade_mod_savepoint(true, 2009042201, 'label'); - } - - // 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 diff --git a/mod/lesson/db/upgrade.php b/mod/lesson/db/upgrade.php index 4e6878345e6..04b0b8f7272 100644 --- a/mod/lesson/db/upgrade.php +++ b/mod/lesson/db/upgrade.php @@ -50,247 +50,13 @@ defined('MOODLE_INTERNAL') || die(); * @global moodle_database $DB * @global core_renderer $OUTPUT * @param int $oldversion - * @return bool + * @return bool */ function xmldb_lesson_upgrade($oldversion) { global $CFG, $DB, $OUTPUT; $dbman = $DB->get_manager(); -//===== 1.9.0 upgrade line ======// - - if ($oldversion < 2007072201) { - - $table = new xmldb_table('lesson'); - $field = new xmldb_field('usegrademax'); - $field2 = new xmldb_field('usemaxgrade'); - - /// Rename lesson->usegrademax to lesson->usemaxgrade. Some old sites can have it incorrect. MDL-13177 - if ($dbman->field_exists($table, $field) && !$dbman->field_exists($table, $field2)) { - /// Set field specs - $field->set_attributes(XMLDB_TYPE_INTEGER, '3', null, XMLDB_NOTNULL, null, '0', 'ongoing'); - /// Launch rename field usegrademax to usemaxgrade - $dbman->rename_field($table, $field, 'usemaxgrade'); - } - - upgrade_mod_savepoint(true, 2007072201, 'lesson'); - } - - if ($oldversion < 2008112601) { - //NOTE: this is a hack, we can not call module lib.php in the middle of upgrade, the necessary db structures/data may not exist yet! - require_once($CFG->dirroot.'/mod/lesson/lib.php'); - - lesson_upgrade_grades(); - - upgrade_mod_savepoint(true, 2008112601, 'lesson'); - } - - if ($oldversion < 2009111600) { - /** - * Change the grade field within lesson_answers to an unsigned int and increment - * the length by one to ensure that no values are changed (reduced) - */ - $table = new xmldb_table('lesson_answers'); - $field = new xmldb_field('grade'); - $field->set_attributes(XMLDB_TYPE_INTEGER, '4', false, XMLDB_NOTNULL, null, '0', 'jumpto'); - $dbman->change_field_type($table, $field); - upgrade_mod_savepoint(true, 2009111600, 'lesson'); - } - - if ($oldversion < 2009120800) { - /** - * Drop the lesson_default table, as of Moodle 2.0 it is no longer used - * the module now has a settings.php instead - */ - $table = new xmldb_table('lesson_default'); - $dbman->drop_table($table); - upgrade_mod_savepoint(true, 2009120800, 'lesson'); - } - - if ($oldversion < 2009120801) { - - /// Define field contentsformat to be added to lesson_pages - $table = new xmldb_table('lesson_pages'); - $field = new xmldb_field('contentsformat', XMLDB_TYPE_INTEGER, '2', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, FORMAT_MOODLE, 'contents'); - - /// Conditionally launch add field contentsformat - if (!$dbman->field_exists($table, $field)) { - $dbman->add_field($table, $field); - } - - // conditionally migrate to html format in contents - if ($CFG->texteditors !== 'textarea') { - $rs = $DB->get_recordset('lesson_pages', array('contentsformat'=>FORMAT_MOODLE), '', 'id,contents,contentsformat'); - foreach ($rs as $lp) { - $lp->contents = text_to_html($lp->contents, false, false, true); - $lp->contentsformat = FORMAT_HTML; - $DB->update_record('lesson_pages', $lp); - upgrade_set_timeout(); - } - $rs->close(); - } - /// lesson savepoint reached - upgrade_mod_savepoint(true, 2009120801, 'lesson'); - } - - if ($oldversion < 2010072000) { - // Define field answerformat to be added to lesson_answers - $table = new xmldb_table('lesson_answers'); - $field = new xmldb_field('answerformat', XMLDB_TYPE_INTEGER, '2', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'answer'); - - // Launch add field answerformat - $dbman->add_field($table, $field); - - // lesson savepoint reached - upgrade_mod_savepoint(true, 2010072000, 'lesson'); - } - - if ($oldversion < 2010072001) { - // Define field responseformat to be added to lesson_answers - $table = new xmldb_table('lesson_answers'); - $field = new xmldb_field('responseformat', XMLDB_TYPE_INTEGER, '2', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'response'); - - // Launch add field responseformat - $dbman->add_field($table, $field); - - // lesson savepoint reached - upgrade_mod_savepoint(true, 2010072001, 'lesson'); - } - - if ($oldversion < 2010072003) { - $rs = $DB->get_recordset('lesson_answers', array()); - foreach ($rs as $answer) { - $flags = intval($answer->flags); - $update = false; - if ($flags & 1) { - $answer->answer = text_to_html($answer->answer, false, false, true); - $answer->answerformat = FORMAT_HTML; - $update = true; - } - if ($flags & 2) { - $answer->response = text_to_html($answer->response, false, false, true); - $answer->responseformat = FORMAT_HTML; - $update = true; - } - if ($update) { - $DB->update_record('lesson_answers', $answer); - } - } - $rs->close(); - upgrade_mod_savepoint(true, 2010072003, 'lesson'); - } - - - if ($oldversion < 2010081200) { - require_once("$CFG->dirroot/mod/lesson/db/upgradelib.php"); - - $sqlfrom = "FROM {lesson} l - JOIN {modules} m ON m.name = 'lesson' - JOIN {course_modules} cm ON (cm.module = m.id AND cm.instance = l.id)"; - - $count = $DB->count_records_sql("SELECT COUNT('x') $sqlfrom"); - - if ($count > 0) { - $rs = $DB->get_recordset_sql("SELECT l.id, l.mediafile, l.course, cm.id AS cmid $sqlfrom ORDER BY l.course, l.id"); - - $pbar = new progress_bar('migratelessonfiles', 500, true); - $fs = get_file_storage(); - - $i = 0; - foreach ($rs as $lesson) { - $i++; - upgrade_set_timeout(120); // set up timeout, may also abort execution - $pbar->update($i, $count, "Migrating lesson files - $i/$count."); - - // fix images incorrectly placed in moddata subfolders, - // this was a really bad decision done by the ppt import developer - if (file_exists("$CFG->dataroot/$lesson->course/moddata/lesson/")) { - lesson_20_migrate_moddata_mixture($lesson->course, '/moddata/lesson/'); - @rmdir("$CFG->dataroot/$lesson->course/moddata/lesson/"); // remove dir if empty - @rmdir("$CFG->dataroot/$lesson->course/moddata/"); // remove dir if empty - } - - // migrate media file only if local course file selected - this is not nice at all, - // it should better be a real block, not a lesson specific hack - if (strpos($lesson->mediafile, '://') !== false) { - // some external URL - - } else if ($lesson->mediafile) { - $context = get_context_instance(CONTEXT_MODULE, $lesson->cmid); - $coursecontext = get_context_instance(CONTEXT_COURSE, $lesson->course); - $filepathname = clean_param('/'.$lesson->mediafile, PARAM_PATH); - $fullpath = "/$context->id/mod_lesson/mediafile/0$filepathname"; - - if ($file = $fs->get_file_by_hash(sha1($fullpath)) and !$file->is_directory()) { - // already converted, just update filename - $DB->set_field('lesson', 'mediafile', $filepathname, array('id'=>$lesson->id)); - } else { - // let's copy file from current course legacy files if possible - $fullpath = "/$coursecontext->id/course/legacy/0$filepathname"; - if ($file = $fs->get_file_by_hash(sha1($fullpath)) and !$file->is_directory()) { - $file_record = array('contextid'=>$context->id, 'component'=>'mod_lesson', 'filearea'=>'mediafile', 'itemid'=>0, 'filepath'=>$file->get_filepath(), 'filename'=>$file->get_filename(), 'sortorder'=>1); - $fs->create_file_from_storedfile($file_record, $file); - $DB->set_field('lesson', 'mediafile', $filepathname, array('id'=>$lesson->id)); - - } else { - // bad luck, no such file exists - $DB->set_field('lesson', 'mediafile', '', array('id'=>$lesson->id)); - } - } - } - } - $rs->close(); - } - - upgrade_mod_savepoint(true, 2010081200, 'lesson'); - } - - - if ($oldversion < 2010121400) { - // Fix matching question pages. - // In Moodle 1.9 matching question pages stored the correct and incorrect - // jumps on the third and forth answers, in Moodle 2.0 they are stored - // in the first and second answers. - // This upgrade block detects matching questions where this is the case - // and fixed it by making firstjump = thirdjump && secondjump = forthjump. - $pages = $DB->get_recordset('lesson_pages', array('qtype'=>'5')); - foreach ($pages as $page) { - $answers = $DB->get_records('lesson_answers', array('pageid'=>$page->id), 'id', 'id, jumpto', 0, 4); - if (count($answers) < 4) { - // If there are less then four answers the problem wont exist. - // All Moodle 1.9 matching questions had a least 4 answers. - continue; - } - $first = array_shift($answers); - $second = array_shift($answers); - $third = array_shift($answers); - $forth = array_shift($answers); - if ($first->jumpto !== '0' || $second->jumpto !== '0') { - // If either are set to something other than the next page then - // there is no problem. - continue; - } - if ($third->jumpto !== '0') { - $first->jumpto = $third->jumpto; - $DB->update_record('lesson_answers', $first); - $third->jumpto = '0'; - $DB->update_record('lesson_answers', $third); - } - if ($forth->jumpto !== '0') { - $second->jumpto = $forth->jumpto; - $DB->update_record('lesson_answers', $second); - $forth->jumpto = '0'; - $DB->update_record('lesson_answers', $forth); - } - } - // Close the record set - $pages->close(); - - upgrade_mod_savepoint(true, 2010121400, 'lesson'); - } - - // 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 diff --git a/mod/lesson/db/upgradelib.php b/mod/lesson/db/upgradelib.php deleted file mode 100644 index 782623f30b3..00000000000 --- a/mod/lesson/db/upgradelib.php +++ /dev/null @@ -1,86 +0,0 @@ -. - -/** - * Resource module upgrade related helper functions - * - * @package mod - * @subpackage lesson - * @copyright 2010 Petr Skoda {@link http://skodak.org} - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ - -defined('MOODLE_INTERNAL') || die; - -/** - * Migrate lesson images incorrectly placed into moddata folder, - * the images were stored in random directories ignoring all coding rules. - * - * @return void - */ -function lesson_20_migrate_moddata_mixture($courseid, $path) { - global $CFG, $DB, $OUTPUT; - - $fullpathname = "$CFG->dataroot/$courseid".$path; - - if (!file_exists($fullpathname)) { - return; - } - - $context = get_context_instance(CONTEXT_COURSE, $courseid); - $items = new DirectoryIterator($fullpathname); - $fs = get_file_storage(); - - foreach ($items as $item) { - if ($item->isDot()) { - // skip - continue; - } - - if ($item->isFile()) { - if (!$item->isReadable()) { - echo $OUTPUT->notification(" File not readable, skipping: ".$courseid.$path.$item->getFilename()); - continue; - } - - $filepath = clean_param($path, PARAM_PATH); - $filename = clean_param($item->getFilename(), PARAM_FILE); - - if ($filename === '') { - //unsupported chars, sorry - continue; - } - - if (!$fs->file_exists($context->id, 'course', 'legacy', '0', $filepath, $filename)) { - $file_record = array('contextid'=>$context->id, 'component'=>'course', 'filearea'=>'legacy', 'itemid'=>0, 'filepath'=>$filepath, 'filename'=>$filename, - 'timecreated'=>$item->getCTime(), 'timemodified'=>$item->getMTime()); - $fs->create_file_from_pathname($file_record, $fullpathname.$item->getFilename()); - @unlink($fullpathname.$item->getFilename()); - } - - } else { - //migrate recursively all subdirectories - lesson_20_migrate_moddata_mixture($courseid, $path.$item->getFilename().'/'); - } - } - - unset($item); //release file handles - unset($items); //release file handles - - // delete dir if empty - @rmdir($fullpathname); -} \ No newline at end of file diff --git a/mod/lti/db/upgrade.php b/mod/lti/db/upgrade.php index e215d0360f1..2b5f1bc4045 100644 --- a/mod/lti/db/upgrade.php +++ b/mod/lti/db/upgrade.php @@ -64,19 +64,6 @@ function xmldb_lti_upgrade($oldversion) { $dbman = $DB->get_manager(); - if ($oldversion < 2011111600){ - // Rename showdescription to showdescriptionlaunch to not conflict with setting from core Moodle - // Rename showtitle as well to be consistent - $table = new xmldb_table('lti'); - $field = new xmldb_field('showtitle', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'debuglaunch'); - - $dbman->rename_field($table, $field, 'showtitlelaunch'); - - $field = new xmldb_field('showdescription', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'showtitlelaunch'); - $dbman->rename_field($table, $field, 'showdescriptionlaunch'); - - upgrade_mod_savepoint(true, 2011111600, 'lti'); - } // Moodle v2.2.0 release upgrade line // Put any upgrade step following this diff --git a/mod/page/db/install.php b/mod/page/db/install.php index cb9b3279a94..071494811b6 100644 --- a/mod/page/db/install.php +++ b/mod/page/db/install.php @@ -34,17 +34,4 @@ defined('MOODLE_INTERNAL') || die; function xmldb_page_install() { global $CFG; - // Upgrade from old resource module type if needed - require_once("$CFG->dirroot/mod/page/db/upgradelib.php"); - page_20_migrate(); - -} - -function xmldb_page_install_recovery() { - global $CFG; - - // Upgrade from old resource module type if needed - require_once("$CFG->dirroot/mod/page/db/upgradelib.php"); - page_20_migrate(); - } diff --git a/mod/page/db/upgrade.php b/mod/page/db/upgrade.php index 72d249772ce..4a81df92a7a 100644 --- a/mod/page/db/upgrade.php +++ b/mod/page/db/upgrade.php @@ -48,12 +48,9 @@ defined('MOODLE_INTERNAL') || die; function xmldb_page_upgrade($oldversion) { global $CFG, $DB; - require_once("$CFG->dirroot/mod/page/db/upgradelib.php"); $dbman = $DB->get_manager(); - // 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 diff --git a/mod/page/db/upgradelib.php b/mod/page/db/upgradelib.php deleted file mode 100644 index 3ffeb7aa366..00000000000 --- a/mod/page/db/upgradelib.php +++ /dev/null @@ -1,147 +0,0 @@ -. - -/** - * Folder module upgrade related helper functions - * - * @package mod - * @subpackage page - * @copyright 2009 Petr Skoda (http://skodak.org) - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ - -defined('MOODLE_INTERNAL') || die; - -/** - * Migrate page module data from 1.9 resource_old table to new page table - * @return void - */ -function page_20_migrate() { - global $CFG, $DB; - require_once("$CFG->libdir/filelib.php"); - require_once("$CFG->libdir/resourcelib.php"); - require_once("$CFG->dirroot/course/lib.php"); - - if (!file_exists("$CFG->dirroot/mod/resource/db/upgradelib.php")) { - // bad luck, somebody deleted resource module - return; - } - - require_once("$CFG->dirroot/mod/resource/db/upgradelib.php"); - - // create resource_old table and copy resource table there if needed - if (!resource_20_prepare_migration()) { - // no modules or fresh install - return; - } - - $fs = get_file_storage(); - - $candidates = $DB->get_recordset('resource_old', array('type'=>'html', 'migrated'=>0)); - foreach ($candidates as $candidate) { - page_20_migrate_candidate($candidate, $fs, FORMAT_HTML); - } - $candidates->close(); - - $candidates = $DB->get_recordset('resource_old', array('type'=>'text', 'migrated'=>0)); - foreach ($candidates as $candidate) { - //there might be some rubbish instead of format int value - $format = (int)$candidate->reference; - if ($format < 0 or $format > 4) { - $format = FORMAT_MOODLE; - } - page_20_migrate_candidate($candidate, $fs, $format); - } - $candidates->close(); - - // clear all course modinfo caches - rebuild_course_cache(0, true); - -} - -function page_20_migrate_candidate($candidate, $fs, $format) { - global $CFG, $DB; - upgrade_set_timeout(); - - if ($CFG->texteditors !== 'textarea') { - $intro = text_to_html($candidate->intro, false, false, true); - $introformat = FORMAT_HTML; - } else { - $intro = $candidate->intro; - $introformat = FORMAT_MOODLE; - } - - $page = new stdClass(); - $page->course = $candidate->course; - $page->name = $candidate->name; - $page->intro = $intro; - $page->introformat = $introformat; - $page->content = $candidate->alltext; - $page->contentformat = $format; - $page->revision = 1; - $page->timemodified = time(); - - // convert links to old course files - let the automigration do the actual job - $usedfiles = array("$CFG->wwwroot/file.php/$page->course/", "$CFG->wwwroot/file.php?file=/$page->course/"); - $page->content = str_ireplace($usedfiles, '@@PLUGINFILE@@/', $page->content); - if (strpos($page->content, '@@PLUGINFILE@@/') === false) { - $page->legacyfiles = RESOURCELIB_LEGACYFILES_NO; - } else { - $page->legacyfiles = RESOURCELIB_LEGACYFILES_ACTIVE; - } - - $options = array('printheading'=>0, 'printintro'=>0); - if ($candidate->popup) { - $page->display = RESOURCELIB_DISPLAY_POPUP; - if ($candidate->popup) { - $rawoptions = explode(',', $candidate->popup); - foreach ($rawoptions as $rawoption) { - list($name, $value) = explode('=', trim($rawoption), 2); - if ($value > 0 and ($name == 'width' or $name == 'height')) { - $options['popup'.$name] = $value; - continue; - } - } - } - } else { - $page->display = RESOURCELIB_DISPLAY_OPEN; - } - $page->displayoptions = serialize($options); - - $page = resource_migrate_to_module('page', $candidate, $page); - - // now try to migrate files from site files - // note: this can not work for html pages or files with other relatively linked files :-( - $siteid = get_site()->id; - if (preg_match_all("|$CFG->wwwroot/file.php(\?file=)?/$siteid(/[^\s'\"&\?#]+)|", $page->content, $matches)) { - $context = get_context_instance(CONTEXT_MODULE, $candidate->cmid); - $sitecontext = get_context_instance(CONTEXT_COURSE, $siteid); - $file_record = array('contextid'=>$context->id, 'component'=>'mod_page', 'filearea'=>'content', 'itemid'=>0); - $fs = get_file_storage(); - foreach ($matches[2] as $i=>$sitefile) { - if (!$file = $fs->get_file_by_hash(sha1("/$sitecontext->id/course/legacy/0".$sitefile))) { - continue; - } - try { - $fs->create_file_from_storedfile($file_record, $file); - $page->content = str_replace($matches[0][$i], '@@PLUGINFILE@@'.$sitefile, $page->content); - } catch (Exception $x) { - } - } - $DB->update_record('page', $page); - } -} diff --git a/mod/quiz/db/upgrade.php b/mod/quiz/db/upgrade.php index d60c06a8b81..367448ea0a5 100644 --- a/mod/quiz/db/upgrade.php +++ b/mod/quiz/db/upgrade.php @@ -36,1162 +36,6 @@ function xmldb_quiz_upgrade($oldversion) { $dbman = $DB->get_manager(); - //===== 1.9.0 upgrade line ======// - - if ($oldversion < 2008062000) { - - // Define table quiz_report to be created - $table = new xmldb_table('quiz_report'); - - // Adding fields to table quiz_report - $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); - - // Adding keys to table quiz_report - $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); - - // Conditionally launch create table for quiz_report - if (!$dbman->table_exists($table)) { - $dbman->create_table($table); - } - - upgrade_mod_savepoint(true, 2008062000, 'quiz'); - } - - if ($oldversion < 2008062001) { - $reporttoinsert = new stdClass(); - $reporttoinsert->name = 'overview'; - $reporttoinsert->displayorder = 10000; - $DB->insert_record('quiz_report', $reporttoinsert); - - $reporttoinsert = new stdClass(); - $reporttoinsert->name = 'responses'; - $reporttoinsert->displayorder = 9000; - $DB->insert_record('quiz_report', $reporttoinsert); - - $reporttoinsert = new stdClass(); - $reporttoinsert->name = 'regrade'; - $reporttoinsert->displayorder = 7000; - $DB->insert_record('quiz_report', $reporttoinsert); - - $reporttoinsert = new stdClass(); - $reporttoinsert->name = 'grading'; - $reporttoinsert->displayorder = 6000; - $DB->insert_record('quiz_report', $reporttoinsert); - - upgrade_mod_savepoint(true, 2008062001, 'quiz'); - } - - if ($oldversion < 2008072402) { - - // Define field lastcron to be added to quiz_report - $table = new xmldb_table('quiz_report'); - $field = new xmldb_field('lastcron', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, - XMLDB_NOTNULL, null, '0', 'displayorder'); - - // Conditionally launch add field lastcron - if (!$dbman->field_exists($table, $field)) { - $dbman->add_field($table, $field); - } - - // Define field cron to be added to quiz_report - $field = new xmldb_field('cron', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, - XMLDB_NOTNULL, null, '0', 'lastcron'); - - // Conditionally launch add field cron - if (!$dbman->field_exists($table, $field)) { - $dbman->add_field($table, $field); - } - - // quiz savepoint reached - upgrade_mod_savepoint(true, 2008072402, 'quiz'); - } - - if ($oldversion < 2008072900) { - // Delete the regrade report - it is now part of the overview report. - $DB->delete_records('quiz_report', array('name' => 'regrade')); - - // quiz savepoint reached - upgrade_mod_savepoint(true, 2008072900, 'quiz'); - } - - if ($oldversion < 2008081500) { - // Define table quiz_question_versions to be dropped - $table = new xmldb_table('quiz_question_versions'); - - // Launch drop table for quiz_question_versions - $dbman->drop_table($table); - - // quiz savepoint reached - upgrade_mod_savepoint(true, 2008081500, 'quiz'); - } - - // Changing the type of all the columns that store grades to be NUMBER(10, 5) or similar. - if ($oldversion < 2008081501) { - // First set all quiz.sumgrades to 0 if they are null. This should never - // happen however some users have encountered a null value there. - $DB->execute('UPDATE {quiz} SET sumgrades=0 WHERE sumgrades IS NULL'); - $table = new xmldb_table('quiz'); - $field = new xmldb_field('sumgrades', XMLDB_TYPE_NUMBER, '10, 5', null, - XMLDB_NOTNULL, null, '0', 'questions'); - $dbman->change_field_type($table, $field); - upgrade_mod_savepoint(true, 2008081501, 'quiz'); - } - - if ($oldversion < 2008081502) { - $table = new xmldb_table('quiz'); - $field = new xmldb_field('grade', XMLDB_TYPE_NUMBER, '10, 5', null, - XMLDB_NOTNULL, null, '0', 'sumgrades'); - $dbman->change_field_type($table, $field); - upgrade_mod_savepoint(true, 2008081502, 'quiz'); - } - - if ($oldversion < 2008081503) { - // First set all quiz.sumgrades to 0 if they are null. This should never - // happen however some users have encountered a null value there. - $DB->execute('UPDATE {quiz_attempts} SET sumgrades=0 WHERE sumgrades IS NULL'); - $table = new xmldb_table('quiz_attempts'); - $field = new xmldb_field('sumgrades', XMLDB_TYPE_NUMBER, '10, 5', null, - XMLDB_NOTNULL, null, '0', 'attempt'); - $dbman->change_field_type($table, $field); - upgrade_mod_savepoint(true, 2008081503, 'quiz'); - } - - if ($oldversion < 2008081504) { - $table = new xmldb_table('quiz_feedback'); - $field = new xmldb_field('mingrade', XMLDB_TYPE_NUMBER, '10, 5', null, - XMLDB_NOTNULL, null, '0', 'feedbacktext'); - $dbman->change_field_type($table, $field); - upgrade_mod_savepoint(true, 2008081504, 'quiz'); - } - - if ($oldversion < 2008081505) { - $table = new xmldb_table('quiz_feedback'); - $field = new xmldb_field('maxgrade', XMLDB_TYPE_NUMBER, '10, 5', null, - XMLDB_NOTNULL, null, '0', 'mingrade'); - $dbman->change_field_type($table, $field); - upgrade_mod_savepoint(true, 2008081505, 'quiz'); - } - - if ($oldversion < 2008081506) { - $table = new xmldb_table('quiz_grades'); - $field = new xmldb_field('grade', XMLDB_TYPE_NUMBER, '10, 5', null, - XMLDB_NOTNULL, null, '0', 'userid'); - $dbman->change_field_type($table, $field); - upgrade_mod_savepoint(true, 2008081506, 'quiz'); - } - - if ($oldversion < 2008081507) { - $table = new xmldb_table('quiz_question_instances'); - $field = new xmldb_field('grade', XMLDB_TYPE_NUMBER, '12, 7', null, - XMLDB_NOTNULL, null, '0', 'question'); - $dbman->change_field_type($table, $field); - upgrade_mod_savepoint(true, 2008081507, 'quiz'); - } - - // Move all of the quiz config settings from $CFG to the config_plugins table. - if ($oldversion < 2008082200) { - foreach (get_object_vars($CFG) as $name => $value) { - if (strpos($name, 'quiz_') === 0) { - $shortname = substr($name, 5); - if ($shortname == 'fix_adaptive') { - // Special case - remove old inconsistency. - $shortname == 'fix_optionflags'; - } - set_config($shortname, $value, 'quiz'); - unset_config($name); - } - } - upgrade_mod_savepoint(true, 2008082200, 'quiz'); - } - - // Now that the quiz is no longer responsible for creating all the question - // bank tables, and some of the tables are now the responsibility of the - // datasetdependent question type, which did not have a version.php file before, - // we need to say that these tables are already installed, otherwise XMLDB - // will try to create them again and give an error. - if ($oldversion < 2008082600) { - // Since MDL-16505 was fixed, and we eliminated the datasetdependent - // question type, this is now a no-op. - upgrade_mod_savepoint(true, 2008082600, 'quiz'); - } - - if ($oldversion < 2008112101) { - - // Define field lastcron to be added to quiz_report - $table = new xmldb_table('quiz_report'); - $field = new xmldb_field('capability', XMLDB_TYPE_CHAR, '255', null, - null, null, null, 'cron'); - - // Conditionally launch add field lastcron - if (!$dbman->field_exists($table, $field)) { - $dbman->add_field($table, $field); - } - - // quiz savepoint reached - upgrade_mod_savepoint(true, 2008112101, 'quiz'); - } - - if ($oldversion < 2009010700) { - - // Define field showuserpicture to be added to quiz - $table = new xmldb_table('quiz'); - $field = new xmldb_field('showuserpicture', XMLDB_TYPE_INTEGER, '4', null, - XMLDB_NOTNULL, null, '0', 'delay2'); - - // Conditionally launch add field showuserpicture - if (!$dbman->field_exists($table, $field)) { - $dbman->add_field($table, $field); - } - - // quiz savepoint reached - upgrade_mod_savepoint(true, 2009010700, 'quiz'); - } - - if ($oldversion < 2009030900) { - // If there are no quiz settings set to advanced yet, the set up the default - // advanced fields from Moodle 2.0. - $quizconfig = get_config('quiz'); - $arealreadyadvanced = false; - foreach (array($quizconfig) as $name => $value) { - if (strpos($name, 'fix_') === 0 && !empty($value)) { - $arealreadyadvanced = true; - break; - } - } - - if (!$arealreadyadvanced) { - set_config('fix_penaltyscheme', 1, 'quiz'); - set_config('fix_attemptonlast', 1, 'quiz'); - set_config('fix_questiondecimalpoints', 1, 'quiz'); - set_config('fix_password', 1, 'quiz'); - set_config('fix_subnet', 1, 'quiz'); - set_config('fix_delay1', 1, 'quiz'); - set_config('fix_delay2', 1, 'quiz'); - set_config('fix_popup', 1, 'quiz'); - } - - // quiz savepoint reached - upgrade_mod_savepoint(true, 2009030900, 'quiz'); - } - - if ($oldversion < 2009031000) { - // Add new questiondecimaldigits setting, separate form the overall decimaldigits one. - $table = new xmldb_table('quiz'); - $field = new xmldb_field('questiondecimalpoints', XMLDB_TYPE_INTEGER, '4', null, - XMLDB_NOTNULL, null, '-2', 'decimalpoints'); - if (!$dbman->field_exists($table, $field)) { - $dbman->add_field($table, $field); - } - - // quiz savepoint reached - upgrade_mod_savepoint(true, 2009031000, 'quiz'); - } - - if ($oldversion < 2009031001) { - // Convert quiz.timelimit from minutes to seconds. - $DB->execute('UPDATE {quiz} SET timelimit = timelimit * 60'); - $default = get_config('quiz', 'timelimit'); - set_config('timelimit', 60 * $default, 'quiz'); - - // quiz savepoint reached - upgrade_mod_savepoint(true, 2009031001, 'quiz'); - } - - if ($oldversion < 2009042000) { - - // Define field introformat to be added to quiz - $table = new xmldb_table('quiz'); - $field = new xmldb_field('introformat', XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, - XMLDB_NOTNULL, null, '0', 'intro'); - - 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('quiz', array('introformat' => FORMAT_MOODLE), - '', 'id, intro, introformat'); - foreach ($rs as $q) { - $q->intro = text_to_html($q->intro, false, false, true); - $q->introformat = FORMAT_HTML; - $DB->update_record('quiz', $q); - upgrade_set_timeout(); - } - $rs->close(); - } - - // quiz savepoint reached - upgrade_mod_savepoint(true, 2009042000, 'quiz'); - } - - if ($oldversion < 2010030501) { - // Define table quiz_overrides to be created - $table = new xmldb_table('quiz_overrides'); - - // Adding fields to table quiz_overrides - $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, - XMLDB_NOTNULL, XMLDB_SEQUENCE, null); - $table->add_field('quiz', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, - XMLDB_NOTNULL, null, '0'); - $table->add_field('groupid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, - null, null, null); - $table->add_field('userid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, - null, null, null); - $table->add_field('timeopen', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, - null, null, null); - $table->add_field('timeclose', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, - null, null, null); - $table->add_field('timelimit', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, - null, null, null); - $table->add_field('attempts', XMLDB_TYPE_INTEGER, '6', XMLDB_UNSIGNED, - null, null, null); - $table->add_field('password', XMLDB_TYPE_CHAR, '255', null, null, null, null); - - // Adding keys to table quiz_overrides - $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); - $table->add_key('quiz', XMLDB_KEY_FOREIGN, array('quiz'), 'quiz', array('id')); - $table->add_key('groupid', XMLDB_KEY_FOREIGN, array('groupid'), 'groups', array('id')); - $table->add_key('userid', XMLDB_KEY_FOREIGN, array('userid'), 'user', array('id')); - - // Conditionally launch create table for quiz_overrides - if (!$dbman->table_exists($table)) { - $dbman->create_table($table); - } - - // quiz savepoint reached - upgrade_mod_savepoint(true, 2010030501, 'quiz'); - } - - if ($oldversion < 2010051800) { - - // Define field showblocks to be added to quiz - $table = new xmldb_table('quiz'); - $field = new xmldb_field('showblocks', XMLDB_TYPE_INTEGER, '4', null, - XMLDB_NOTNULL, null, '0', 'showuserpicture'); - - // Conditionally launch add field showblocks - if (!$dbman->field_exists($table, $field)) { - $dbman->add_field($table, $field); - } - - // quiz savepoint reached - upgrade_mod_savepoint(true, 2010051800, 'quiz'); - } - - if ($oldversion < 2010080600) { - - // Define field feedbacktextformat to be added to quiz_feedback - $table = new xmldb_table('quiz_feedback'); - $field = new xmldb_field('feedbacktextformat', XMLDB_TYPE_INTEGER, '2', null, - XMLDB_NOTNULL, null, '0', 'feedbacktext'); - - // Conditionally launch add field feedbacktextformat - if (!$dbman->field_exists($table, $field)) { - $dbman->add_field($table, $field); - } - - // This column defaults to FORMAT_MOODLE, which is correct. - - // quiz savepoint reached - upgrade_mod_savepoint(true, 2010080600, 'quiz'); - } - - if ($oldversion < 2010102000) { - - // Define field showblocks to be added to quiz - // Repeat this step, because the column was missing from install.xml for a time. - $table = new xmldb_table('quiz'); - $field = new xmldb_field('showblocks', XMLDB_TYPE_INTEGER, '4', null, - XMLDB_NOTNULL, null, '0', 'showuserpicture'); - - // Conditionally launch add field showblocks - if (!$dbman->field_exists($table, $field)) { - $dbman->add_field($table, $field); - } - - // quiz savepoint reached - upgrade_mod_savepoint(true, 2010102000, 'quiz'); - } - - if ($oldversion < 2010122300) { - // Fix quiz in the post table after upgrade from 1.9 - $table = new xmldb_table('quiz'); - $columns = $DB->get_columns('quiz'); - - // quiz.questiondecimalpoints should be int (4) not null default -2 - if (array_key_exists('questiondecimalpoints', $columns) && - $columns['questiondecimalpoints']->default_value != '-2') { - $field = new xmldb_field('questiondecimalpoints', XMLDB_TYPE_INTEGER, '4', null, - XMLDB_NOTNULL, null, -2, 'decimalpoints'); - if ($dbman->field_exists($table, $field)) { - $dbman->change_field_default($table, $field); - } - } - - // quiz.sumgrades should be decimal(10, 5) not null default 0 - if (array_key_exists('sumgrades', $columns) && empty($columns['sumgrades']->not_null)) { - // First set all quiz.sumgrades to 0 if they are null. This should never - // happen however some users have encountered a null value there. - $DB->execute('UPDATE {quiz} SET sumgrades=0 WHERE sumgrades IS NULL'); - - $field = new xmldb_field('sumgrades', XMLDB_TYPE_NUMBER, '10, 5', null, - XMLDB_NOTNULL, null, '0', 'questions'); - if ($dbman->field_exists($table, $field)) { - $dbman->change_field_default($table, $field); - } - } - - // quiz.grade should be decimal(10, 5) not null default 0 - if (array_key_exists('grade', $columns) && empty($columns['grade']->not_null)) { - $field = new xmldb_field('grade', XMLDB_TYPE_NUMBER, '10, 5', null, - XMLDB_NOTNULL, null, '0', 'sumgrades'); - if ($dbman->field_exists($table, $field)) { - $dbman->change_field_default($table, $field); - } - } - - upgrade_mod_savepoint(true, 2010122300, 'quiz'); - } - - if ($oldversion < 2010122301) { - // Fix quiz_attempts in the post table after upgrade from 1.9 - $table = new xmldb_table('quiz_attempts'); - $columns = $DB->get_columns('quiz_attempts'); - - // quiz_attempts.sumgrades should be decimal(10, 5) not null default 0 - if (array_key_exists('sumgrades', $columns) && empty($columns['sumgrades']->not_null)) { - // First set all quiz.sumgrades to 0 if they are null. This should never - // happen however some users have encountered a null value there. - $DB->execute('UPDATE {quiz_attempts} SET sumgrades=0 WHERE sumgrades IS NULL'); - - $field = new xmldb_field('sumgrades', XMLDB_TYPE_NUMBER, '10, 5', null, - XMLDB_NOTNULL, null, '0', 'attempt'); - if ($dbman->field_exists($table, $field)) { - $dbman->change_field_default($table, $field); - } - } - - upgrade_mod_savepoint(true, 2010122301, 'quiz'); - } - - if ($oldversion < 2010122302) { - // Fix quiz_feedback in the post table after upgrade from 1.9 - $table = new xmldb_table('quiz_feedback'); - $columns = $DB->get_columns('quiz_feedback'); - - // quiz_feedback.mingrade should be decimal(10, 5) not null default 0 - if (array_key_exists('mingrade', $columns) && empty($columns['mingrade']->not_null)) { - $field = new xmldb_field('mingrade', XMLDB_TYPE_NUMBER, '10, 5', null, - XMLDB_NOTNULL, null, '0', 'feedbacktextformat'); - if ($dbman->field_exists($table, $field)) { - $dbman->change_field_default($table, $field); - } - } - - // quiz_feedback.maxgrade should be decimal(10, 5) not null default 0 - if (array_key_exists('maxgrade', $columns) && empty($columns['maxgrade']->not_null)) { - // Fixed in earlier upgrade code - $field = new xmldb_field('maxgrade', XMLDB_TYPE_NUMBER, '10, 5', null, - XMLDB_NOTNULL, null, '0', 'mingrade'); - if ($dbman->field_exists($table, $field)) { - $dbman->change_field_default($table, $field); - } - } - - upgrade_mod_savepoint(true, 2010122302, 'quiz'); - } - - if ($oldversion < 2010122303) { - // Fix quiz_grades in the post table after upgrade from 1.9 - $table = new xmldb_table('quiz_grades'); - $columns = $DB->get_columns('quiz_grades'); - - // quiz_grades.grade should be decimal(10, 5) not null default 0 - if (array_key_exists('grade', $columns) && empty($columns['grade']->not_null)) { - $field = new xmldb_field('grade', XMLDB_TYPE_NUMBER, '10, 5', null, - XMLDB_NOTNULL, null, '0', 'userid'); - if ($dbman->field_exists($table, $field)) { - $dbman->change_field_default($table, $field); - } - } - - upgrade_mod_savepoint(true, 2010122303, 'quiz'); - } - - if ($oldversion < 2010122304) { - // Fix quiz_question_instances in the post table after upgrade from 1.9 - $table = new xmldb_table('quiz_question_instances'); - $columns = $DB->get_columns('quiz_question_instances'); - - // quiz_question_instances.grade should be decimal(12, 7) not null default 0 - if (array_key_exists('grade', $columns) && empty($columns['grade']->not_null)) { - $field = new xmldb_field('grade', XMLDB_TYPE_NUMBER, '12, 7', null, - XMLDB_NOTNULL, null, '0', 'question'); - if ($dbman->field_exists($table, $field)) { - $dbman->change_field_default($table, $field); - } - } - - upgrade_mod_savepoint(true, 2010122304, 'quiz'); - } - - //===== 2.1.0 upgrade line ======// - - // Complete any old upgrade from 1.5 that was never finished. - if ($oldversion < 2011051199) { - $table = new xmldb_table('question_states'); - if ($dbman->table_exists($table)) { - $transaction = $DB->start_delegated_transaction(); - - $oldattempts = $DB->get_records_sql(' - SELECT * - FROM {quiz_attempts} quiza - WHERE uniqueid IN ( - SELECT DISTINCT qst.attempt - FROM {question_states} qst - LEFT JOIN {question_sessions} qsess ON - qst.question = qsess.questionid AND qst.attempt = qsess.attemptid - WHERE qsess.id IS NULL - ) - '); - - if ($oldattempts) { - require_once($CFG->dirroot . '/mod/quiz/db/upgradelib.php'); - - $pbar = new progress_bar('q15upgrade'); - $pbar->create(); - $a = new stdClass(); - $a->outof = count($oldattempts); - $a->done = 0; - $pbar->update($a->done, $a->outof, - get_string('upgradingveryoldquizattempts', 'quiz', $a)); - - foreach ($oldattempts as $oldattempt) { - quiz_upgrade_very_old_question_sessions($oldattempt); - - $a->done += 1; - $pbar->update($a->done, $a->outof, - get_string('upgradingveryoldquizattempts', 'quiz', $a)); - } - } - - $transaction->allow_commit(); - } - - // quiz savepoint reached - upgrade_mod_savepoint(true, 2011051199, 'quiz'); - } - - // Add new preferredbehaviour column to the quiz table. - if ($oldversion < 2011051200) { - $table = new xmldb_table('quiz'); - $field = new xmldb_field('preferredbehaviour'); - $field->set_attributes(XMLDB_TYPE_CHAR, '32', null, - null, null, null, 'timeclose'); - if (!$dbman->field_exists($table, $field)) { - $dbman->add_field($table, $field); - } - - // quiz savepoint reached - upgrade_mod_savepoint(true, 2011051200, 'quiz'); - } - - // Populate preferredbehaviour column based on old optionflags column. - if ($oldversion < 2011051201) { - if ($dbman->field_exists('quiz', 'optionflags')) { - $DB->set_field_select('quiz', 'preferredbehaviour', 'deferredfeedback', - 'optionflags = 0'); - $DB->set_field_select('quiz', 'preferredbehaviour', 'adaptive', - 'optionflags <> 0 AND penaltyscheme <> 0'); - $DB->set_field_select('quiz', 'preferredbehaviour', 'adaptivenopenalty', - 'optionflags <> 0 AND penaltyscheme = 0'); - - set_config('preferredbehaviour', 'deferredfeedback', 'quiz'); - set_config('fix_preferredbehaviour', 0, 'quiz'); - } - - // quiz savepoint reached - upgrade_mod_savepoint(true, 2011051201, 'quiz'); - } - - // Add a not-NULL constraint to the preferredmodel field now that it is populated. - if ($oldversion < 2011051202) { - $table = new xmldb_table('quiz'); - $field = new xmldb_field('preferredbehaviour'); - $field->set_attributes(XMLDB_TYPE_CHAR, '32', null, - XMLDB_NOTNULL, null, null, 'timeclose'); - - $dbman->change_field_notnull($table, $field); - - // quiz savepoint reached - upgrade_mod_savepoint(true, 2011051202, 'quiz'); - } - - // Drop the old optionflags field. - if ($oldversion < 2011051203) { - $table = new xmldb_table('quiz'); - $field = new xmldb_field('optionflags'); - - if ($dbman->field_exists($table, $field)) { - $dbman->drop_field($table, $field); - } - - unset_config('optionflags', 'quiz'); - unset_config('fix_optionflags', 'quiz'); - - // quiz savepoint reached - upgrade_mod_savepoint(true, 2011051203, 'quiz'); - } - - // Drop the old penaltyscheme field. - if ($oldversion < 2011051204) { - $table = new xmldb_table('quiz'); - $field = new xmldb_field('penaltyscheme'); - - if ($dbman->field_exists($table, $field)) { - $dbman->drop_field($table, $field); - } - - unset_config('penaltyscheme', 'quiz'); - unset_config('fix_penaltyscheme', 'quiz'); - - // quiz savepoint reached - upgrade_mod_savepoint(true, 2011051204, 'quiz'); - } - - if ($oldversion < 2011051205) { - - // Changing nullability of field sumgrades on table quiz_attempts to null - $table = new xmldb_table('quiz_attempts'); - $field = new xmldb_field('sumgrades'); - $field->set_attributes(XMLDB_TYPE_NUMBER, '10, 5', null, - null, null, null, 'attempt'); - - // Launch change of nullability for field sumgrades - $dbman->change_field_notnull($table, $field); - - // Launch change of default for field sumgrades - $dbman->change_field_default($table, $field); - - // quiz savepoint reached - upgrade_mod_savepoint(true, 2011051205, 'quiz'); - } - - if ($oldversion < 2011051207) { - - // Define field reviewattempt to be added to quiz - $table = new xmldb_table('quiz'); - $field = new xmldb_field('reviewattempt'); - $field->set_attributes(XMLDB_TYPE_INTEGER, '6', XMLDB_UNSIGNED, - XMLDB_NOTNULL, null, '0', 'review'); - - // Launch add field reviewattempt - if (!$dbman->field_exists($table, $field)) { - $dbman->add_field($table, $field); - } - - // quiz savepoint reached - upgrade_mod_savepoint(true, 2011051207, 'quiz'); - } - - if ($oldversion < 2011051208) { - - // Define field reviewattempt to be added to quiz - $table = new xmldb_table('quiz'); - $field = new xmldb_field('reviewcorrectness'); - $field->set_attributes(XMLDB_TYPE_INTEGER, '6', XMLDB_UNSIGNED, - XMLDB_NOTNULL, null, '0', 'reviewattempt'); - - // Launch add field reviewattempt - if (!$dbman->field_exists($table, $field)) { - $dbman->add_field($table, $field); - } - - // quiz savepoint reached - upgrade_mod_savepoint(true, 2011051208, 'quiz'); - } - - if ($oldversion < 2011051209) { - - // Define field reviewattempt to be added to quiz - $table = new xmldb_table('quiz'); - $field = new xmldb_field('reviewmarks'); - $field->set_attributes(XMLDB_TYPE_INTEGER, '6', XMLDB_UNSIGNED, - XMLDB_NOTNULL, null, '0', 'reviewcorrectness'); - - // Launch add field reviewattempt - if (!$dbman->field_exists($table, $field)) { - $dbman->add_field($table, $field); - } - - // quiz savepoint reached - upgrade_mod_savepoint(true, 2011051209, 'quiz'); - } - - if ($oldversion < 2011051210) { - - // Define field reviewattempt to be added to quiz - $table = new xmldb_table('quiz'); - $field = new xmldb_field('reviewspecificfeedback'); - $field->set_attributes(XMLDB_TYPE_INTEGER, '6', XMLDB_UNSIGNED, - XMLDB_NOTNULL, null, '0', 'reviewmarks'); - - // Launch add field reviewattempt - if (!$dbman->field_exists($table, $field)) { - $dbman->add_field($table, $field); - } - - // quiz savepoint reached - upgrade_mod_savepoint(true, 2011051210, 'quiz'); - } - - if ($oldversion < 2011051211) { - - // Define field reviewattempt to be added to quiz - $table = new xmldb_table('quiz'); - $field = new xmldb_field('reviewgeneralfeedback'); - $field->set_attributes(XMLDB_TYPE_INTEGER, '6', XMLDB_UNSIGNED, - XMLDB_NOTNULL, null, '0', 'reviewspecificfeedback'); - - // Launch add field reviewattempt - if (!$dbman->field_exists($table, $field)) { - $dbman->add_field($table, $field); - } - - // quiz savepoint reached - upgrade_mod_savepoint(true, 2011051211, 'quiz'); - } - - if ($oldversion < 2011051212) { - - // Define field reviewattempt to be added to quiz - $table = new xmldb_table('quiz'); - $field = new xmldb_field('reviewrightanswer'); - $field->set_attributes(XMLDB_TYPE_INTEGER, '6', XMLDB_UNSIGNED, - XMLDB_NOTNULL, null, '0', 'reviewgeneralfeedback'); - - // Launch add field reviewattempt - if (!$dbman->field_exists($table, $field)) { - $dbman->add_field($table, $field); - } - - // quiz savepoint reached - upgrade_mod_savepoint(true, 2011051212, 'quiz'); - } - - if ($oldversion < 2011051213) { - - // Define field reviewattempt to be added to quiz - $table = new xmldb_table('quiz'); - $field = new xmldb_field('reviewoverallfeedback'); - $field->set_attributes(XMLDB_TYPE_INTEGER, '6', XMLDB_UNSIGNED, - XMLDB_NOTNULL, null, '0', 'reviewrightanswer'); - - // Launch add field reviewattempt - if (!$dbman->field_exists($table, $field)) { - $dbman->add_field($table, $field); - } - - // quiz savepoint reached - upgrade_mod_savepoint(true, 2011051213, 'quiz'); - } - - define('QUIZ_NEW_DURING', 0x10000); - define('QUIZ_NEW_IMMEDIATELY_AFTER', 0x01000); - define('QUIZ_NEW_LATER_WHILE_OPEN', 0x00100); - define('QUIZ_NEW_AFTER_CLOSE', 0x00010); - - define('QUIZ_OLD_IMMEDIATELY', 0x3c003f); - define('QUIZ_OLD_OPEN', 0x3c00fc0); - define('QUIZ_OLD_CLOSED', 0x3c03f000); - - define('QUIZ_OLD_RESPONSES', 1*0x1041); // Show responses - define('QUIZ_OLD_SCORES', 2*0x1041); // Show scores - define('QUIZ_OLD_FEEDBACK', 4*0x1041); // Show question feedback - define('QUIZ_OLD_ANSWERS', 8*0x1041); // Show correct answers - define('QUIZ_OLD_SOLUTIONS', 16*0x1041); // Show solutions - define('QUIZ_OLD_GENERALFEEDBACK', 32*0x1041); // Show question general feedback - define('QUIZ_OLD_OVERALLFEEDBACK', 1*0x4440000); // Show quiz overall feedback - - // Copy the old review settings - if ($oldversion < 2011051214) { - if ($dbman->field_exists('quiz', 'review')) { - $DB->execute(" - UPDATE {quiz} - SET reviewattempt = " . $DB->sql_bitor($DB->sql_bitor( - QUIZ_NEW_DURING, - 'CASE WHEN ' . $DB->sql_bitand('review', QUIZ_OLD_IMMEDIATELY & QUIZ_OLD_RESPONSES) . - ' <> 0 THEN ' . QUIZ_NEW_IMMEDIATELY_AFTER . ' ELSE 0 END'), $DB->sql_bitor( - 'CASE WHEN ' . $DB->sql_bitand('review', QUIZ_OLD_OPEN & QUIZ_OLD_RESPONSES) . - ' <> 0 THEN ' . QUIZ_NEW_LATER_WHILE_OPEN . ' ELSE 0 END', - 'CASE WHEN ' . $DB->sql_bitand('review', QUIZ_OLD_CLOSED & QUIZ_OLD_RESPONSES) . - ' <> 0 THEN ' . QUIZ_NEW_AFTER_CLOSE . ' ELSE 0 END')) . " - "); - } - - // quiz savepoint reached - upgrade_mod_savepoint(true, 2011051214, 'quiz'); - } - - if ($oldversion < 2011051215) { - if ($dbman->field_exists('quiz', 'review')) { - $DB->execute(" - UPDATE {quiz} - SET reviewcorrectness = " . $DB->sql_bitor($DB->sql_bitor( - QUIZ_NEW_DURING, - 'CASE WHEN ' . $DB->sql_bitand('review', QUIZ_OLD_IMMEDIATELY & QUIZ_OLD_SCORES) . - ' <> 0 THEN ' . QUIZ_NEW_IMMEDIATELY_AFTER . ' ELSE 0 END'), $DB->sql_bitor( - 'CASE WHEN ' . $DB->sql_bitand('review', QUIZ_OLD_OPEN & QUIZ_OLD_SCORES) . - ' <> 0 THEN ' . QUIZ_NEW_LATER_WHILE_OPEN . ' ELSE 0 END', - 'CASE WHEN ' . $DB->sql_bitand('review', QUIZ_OLD_CLOSED & QUIZ_OLD_SCORES) . - ' <> 0 THEN ' . QUIZ_NEW_AFTER_CLOSE . ' ELSE 0 END')) . " - "); - } - - // quiz savepoint reached - upgrade_mod_savepoint(true, 2011051215, 'quiz'); - } - - if ($oldversion < 2011051216) { - if ($dbman->field_exists('quiz', 'review')) { - $DB->execute(" - UPDATE {quiz} - SET reviewmarks = " . $DB->sql_bitor($DB->sql_bitor( - QUIZ_NEW_DURING, - 'CASE WHEN ' . $DB->sql_bitand('review', QUIZ_OLD_IMMEDIATELY & QUIZ_OLD_SCORES) . - ' <> 0 THEN ' . QUIZ_NEW_IMMEDIATELY_AFTER . ' ELSE 0 END'), $DB->sql_bitor( - 'CASE WHEN ' . $DB->sql_bitand('review', QUIZ_OLD_OPEN & QUIZ_OLD_SCORES) . - ' <> 0 THEN ' . QUIZ_NEW_LATER_WHILE_OPEN . ' ELSE 0 END', - 'CASE WHEN ' . $DB->sql_bitand('review', QUIZ_OLD_CLOSED & QUIZ_OLD_SCORES) . - ' <> 0 THEN ' . QUIZ_NEW_AFTER_CLOSE . ' ELSE 0 END')) . " - "); - } - - // quiz savepoint reached - upgrade_mod_savepoint(true, 2011051216, 'quiz'); - } - - if ($oldversion < 2011051217) { - if ($dbman->field_exists('quiz', 'review')) { - $DB->execute(" - UPDATE {quiz} - SET reviewspecificfeedback = " . $DB->sql_bitor($DB->sql_bitor( - 'CASE WHEN ' . $DB->sql_bitand('review', QUIZ_OLD_IMMEDIATELY & QUIZ_OLD_FEEDBACK) . - ' <> 0 THEN ' . QUIZ_NEW_DURING . ' ELSE 0 END', - 'CASE WHEN ' . $DB->sql_bitand('review', QUIZ_OLD_IMMEDIATELY & QUIZ_OLD_FEEDBACK) . - ' <> 0 THEN ' . QUIZ_NEW_IMMEDIATELY_AFTER . ' ELSE 0 END'), $DB->sql_bitor( - 'CASE WHEN ' . $DB->sql_bitand('review', QUIZ_OLD_OPEN & QUIZ_OLD_FEEDBACK) . - ' <> 0 THEN ' . QUIZ_NEW_LATER_WHILE_OPEN . ' ELSE 0 END', - 'CASE WHEN ' . $DB->sql_bitand('review', QUIZ_OLD_CLOSED & QUIZ_OLD_FEEDBACK) . - ' <> 0 THEN ' . QUIZ_NEW_AFTER_CLOSE . ' ELSE 0 END')) . " - "); - } - - // quiz savepoint reached - upgrade_mod_savepoint(true, 2011051217, 'quiz'); - } - - if ($oldversion < 2011051218) { - if ($dbman->field_exists('quiz', 'review')) { - $DB->execute(" - UPDATE {quiz} - SET reviewgeneralfeedback = " . $DB->sql_bitor($DB->sql_bitor( - 'CASE WHEN ' . $DB->sql_bitand('review', QUIZ_OLD_IMMEDIATELY & QUIZ_OLD_GENERALFEEDBACK) . - ' <> 0 THEN ' . QUIZ_NEW_DURING . ' ELSE 0 END', - 'CASE WHEN ' . $DB->sql_bitand('review', QUIZ_OLD_IMMEDIATELY & QUIZ_OLD_GENERALFEEDBACK) . - ' <> 0 THEN ' . QUIZ_NEW_IMMEDIATELY_AFTER . ' ELSE 0 END'), $DB->sql_bitor( - 'CASE WHEN ' . $DB->sql_bitand('review', QUIZ_OLD_OPEN & QUIZ_OLD_GENERALFEEDBACK) . - ' <> 0 THEN ' . QUIZ_NEW_LATER_WHILE_OPEN . ' ELSE 0 END', - 'CASE WHEN ' . $DB->sql_bitand('review', QUIZ_OLD_CLOSED & QUIZ_OLD_GENERALFEEDBACK) . - ' <> 0 THEN ' . QUIZ_NEW_AFTER_CLOSE . ' ELSE 0 END')) . " - "); - } - - // quiz savepoint reached - upgrade_mod_savepoint(true, 2011051218, 'quiz'); - } - - if ($oldversion < 2011051219) { - if ($dbman->field_exists('quiz', 'review')) { - $DB->execute(" - UPDATE {quiz} - SET reviewrightanswer = " . $DB->sql_bitor($DB->sql_bitor( - 'CASE WHEN ' . $DB->sql_bitand('review', QUIZ_OLD_IMMEDIATELY & QUIZ_OLD_ANSWERS) . - ' <> 0 THEN ' . QUIZ_NEW_DURING . ' ELSE 0 END', - 'CASE WHEN ' . $DB->sql_bitand('review', QUIZ_OLD_IMMEDIATELY & QUIZ_OLD_ANSWERS) . - ' <> 0 THEN ' . QUIZ_NEW_IMMEDIATELY_AFTER . ' ELSE 0 END'), $DB->sql_bitor( - 'CASE WHEN ' . $DB->sql_bitand('review', QUIZ_OLD_OPEN & QUIZ_OLD_ANSWERS) . - ' <> 0 THEN ' . QUIZ_NEW_LATER_WHILE_OPEN . ' ELSE 0 END', - 'CASE WHEN ' . $DB->sql_bitand('review', QUIZ_OLD_CLOSED & QUIZ_OLD_ANSWERS) . - ' <> 0 THEN ' . QUIZ_NEW_AFTER_CLOSE . ' ELSE 0 END')) . " - "); - } - - // quiz savepoint reached - upgrade_mod_savepoint(true, 2011051219, 'quiz'); - } - - if ($oldversion < 2011051220) { - if ($dbman->field_exists('quiz', 'review')) { - $DB->execute(" - UPDATE {quiz} - SET reviewoverallfeedback = " . $DB->sql_bitor($DB->sql_bitor( - 0, - 'CASE WHEN ' . $DB->sql_bitand('review', QUIZ_OLD_IMMEDIATELY & QUIZ_OLD_OVERALLFEEDBACK) . - ' <> 0 THEN ' . QUIZ_NEW_IMMEDIATELY_AFTER . ' ELSE 0 END'), $DB->sql_bitor( - 'CASE WHEN ' . $DB->sql_bitand('review', QUIZ_OLD_OPEN & QUIZ_OLD_OVERALLFEEDBACK) . - ' <> 0 THEN ' . QUIZ_NEW_LATER_WHILE_OPEN . ' ELSE 0 END', - 'CASE WHEN ' . $DB->sql_bitand('review', QUIZ_OLD_CLOSED & QUIZ_OLD_OVERALLFEEDBACK) . - ' <> 0 THEN ' . QUIZ_NEW_AFTER_CLOSE . ' ELSE 0 END')) . " - "); - } - - // quiz savepoint reached - upgrade_mod_savepoint(true, 2011051220, 'quiz'); - } - - // And, do the same for the defaults - if ($oldversion < 2011051221) { - $quizrevew = get_config('quiz', 'review'); - if (!empty($quizrevew)) { - - set_config('reviewattempt', - QUIZ_NEW_DURING | - ($quizrevew & QUIZ_OLD_IMMEDIATELY & QUIZ_OLD_RESPONSES ? QUIZ_NEW_IMMEDIATELY_AFTER : 0) | - ($quizrevew & QUIZ_OLD_OPEN & QUIZ_OLD_RESPONSES ? QUIZ_NEW_LATER_WHILE_OPEN : 0) | - ($quizrevew & QUIZ_OLD_CLOSED & QUIZ_OLD_RESPONSES ? QUIZ_NEW_AFTER_CLOSE : 0), - 'quiz'); - - set_config('reviewcorrectness', - QUIZ_NEW_DURING | - ($quizrevew & QUIZ_OLD_IMMEDIATELY & QUIZ_OLD_SCORES ? QUIZ_NEW_IMMEDIATELY_AFTER : 0) | - ($quizrevew & QUIZ_OLD_OPEN & QUIZ_OLD_SCORES ? QUIZ_NEW_LATER_WHILE_OPEN : 0) | - ($quizrevew & QUIZ_OLD_CLOSED & QUIZ_OLD_SCORES ? QUIZ_NEW_AFTER_CLOSE : 0), - 'quiz'); - - set_config('reviewmarks', - QUIZ_NEW_DURING | - ($quizrevew & QUIZ_OLD_IMMEDIATELY & QUIZ_OLD_SCORES ? QUIZ_NEW_IMMEDIATELY_AFTER : 0) | - ($quizrevew & QUIZ_OLD_OPEN & QUIZ_OLD_SCORES ? QUIZ_NEW_LATER_WHILE_OPEN : 0) | - ($quizrevew & QUIZ_OLD_CLOSED & QUIZ_OLD_SCORES ? QUIZ_NEW_AFTER_CLOSE : 0), - 'quiz'); - - set_config('reviewspecificfeedback', - ($quizrevew & QUIZ_OLD_IMMEDIATELY & QUIZ_OLD_FEEDBACK ? QUIZ_NEW_DURING : 0) | - ($quizrevew & QUIZ_OLD_IMMEDIATELY & QUIZ_OLD_FEEDBACK ? QUIZ_NEW_IMMEDIATELY_AFTER : 0) | - ($quizrevew & QUIZ_OLD_OPEN & QUIZ_OLD_FEEDBACK ? QUIZ_NEW_LATER_WHILE_OPEN : 0) | - ($quizrevew & QUIZ_OLD_CLOSED & QUIZ_OLD_FEEDBACK ? QUIZ_NEW_AFTER_CLOSE : 0), - 'quiz'); - - set_config('reviewgeneralfeedback', - ($quizrevew & QUIZ_OLD_IMMEDIATELY & QUIZ_OLD_GENERALFEEDBACK ? QUIZ_NEW_DURING : 0) | - ($quizrevew & QUIZ_OLD_IMMEDIATELY & QUIZ_OLD_GENERALFEEDBACK ? QUIZ_NEW_IMMEDIATELY_AFTER : 0) | - ($quizrevew & QUIZ_OLD_OPEN & QUIZ_OLD_GENERALFEEDBACK ? QUIZ_NEW_LATER_WHILE_OPEN : 0) | - ($quizrevew & QUIZ_OLD_CLOSED & QUIZ_OLD_GENERALFEEDBACK ? QUIZ_NEW_AFTER_CLOSE : 0), - 'quiz'); - - set_config('reviewrightanswer', - ($quizrevew & QUIZ_OLD_IMMEDIATELY & QUIZ_OLD_ANSWERS ? QUIZ_NEW_DURING : 0) | - ($quizrevew & QUIZ_OLD_IMMEDIATELY & QUIZ_OLD_ANSWERS ? QUIZ_NEW_IMMEDIATELY_AFTER : 0) | - ($quizrevew & QUIZ_OLD_OPEN & QUIZ_OLD_ANSWERS ? QUIZ_NEW_LATER_WHILE_OPEN : 0) | - ($quizrevew & QUIZ_OLD_CLOSED & QUIZ_OLD_ANSWERS ? QUIZ_NEW_AFTER_CLOSE : 0), - 'quiz'); - - set_config('reviewoverallfeedback', - 0 | - ($quizrevew & QUIZ_OLD_IMMEDIATELY & QUIZ_OLD_OVERALLFEEDBACK ? QUIZ_NEW_IMMEDIATELY_AFTER : 0) | - ($quizrevew & QUIZ_OLD_OPEN & QUIZ_OLD_OVERALLFEEDBACK ? QUIZ_NEW_LATER_WHILE_OPEN : 0) | - ($quizrevew & QUIZ_OLD_CLOSED & QUIZ_OLD_OVERALLFEEDBACK ? QUIZ_NEW_AFTER_CLOSE : 0), - 'quiz'); - } - - // quiz savepoint reached - upgrade_mod_savepoint(true, 2011051221, 'quiz'); - } - - // Finally drop the old column - if ($oldversion < 2011051222) { - // Define field review to be dropped from quiz - $table = new xmldb_table('quiz'); - $field = new xmldb_field('review'); - - // Launch drop field review - if ($dbman->field_exists($table, $field)) { - $dbman->drop_field($table, $field); - } - - // quiz savepoint reached - upgrade_mod_savepoint(true, 2011051222, 'quiz'); - } - - if ($oldversion < 2011051223) { - unset_config('review', 'quiz'); - - // quiz savepoint reached - upgrade_mod_savepoint(true, 2011051223, 'quiz'); - } - - if ($oldversion < 2011051225) { - // Define table quiz_report to be renamed to quiz_reports - $table = new xmldb_table('quiz_report'); - - // Launch rename table for quiz_reports - if ($dbman->table_exists($table)) { - $dbman->rename_table($table, 'quiz_reports'); - } - - upgrade_mod_savepoint(true, 2011051225, 'quiz'); - } - - if ($oldversion < 2011051226) { - // Define index name (unique) to be added to quiz_reports - $table = new xmldb_table('quiz_reports'); - $index = new xmldb_index('name', XMLDB_INDEX_UNIQUE, array('name')); - - // Conditionally launch add index name - if (!$dbman->index_exists($table, $index)) { - $dbman->add_index($table, $index); - } - - upgrade_mod_savepoint(true, 2011051226, 'quiz'); - } - - if ($oldversion < 2011051227) { - - // Changing nullability of field sumgrades on table quiz_attempts to null - $table = new xmldb_table('quiz_attempts'); - $field = new xmldb_field('sumgrades', XMLDB_TYPE_NUMBER, '10, 5', null, - null, null, null, 'attempt'); - - // Launch change of nullability for field sumgrades - $dbman->change_field_notnull($table, $field); - - // quiz savepoint reached - upgrade_mod_savepoint(true, 2011051227, 'quiz'); - } - - if ($oldversion < 2011051228) { - // Define field needsupgradetonewqe to be added to quiz_attempts - $table = new xmldb_table('quiz_attempts'); - $field = new xmldb_field('needsupgradetonewqe', XMLDB_TYPE_INTEGER, '3', XMLDB_UNSIGNED, - XMLDB_NOTNULL, null, '0', 'preview'); - - // Launch add field needsupgradetonewqe - if (!$dbman->field_exists($table, $field)) { - $dbman->add_field($table, $field); - } - - $DB->set_field('quiz_attempts', 'needsupgradetonewqe', 1); - - // quiz savepoint reached - upgrade_mod_savepoint(true, 2011051228, 'quiz'); - } - - if ($oldversion < 2011051229) { - $table = new xmldb_table('question_states'); - if ($dbman->table_exists($table)) { - // First delete all data from preview attempts. - $DB->delete_records_select('question_states', - "attempt IN (SELECT uniqueid FROM {quiz_attempts} WHERE preview = 1)"); - $DB->delete_records_select('question_sessions', - "attemptid IN (SELECT uniqueid FROM {quiz_attempts} WHERE preview = 1)"); - $DB->delete_records('quiz_attempts', array('preview' => 1)); - - // Now update all the old attempt data. - $oldrcachesetting = $CFG->rcache; - $CFG->rcache = false; - - require_once($CFG->dirroot . '/question/engine/upgrade/upgradelib.php'); - $upgrader = new question_engine_attempt_upgrader(); - $upgrader->convert_all_quiz_attempts(); - - $CFG->rcache = $oldrcachesetting; - } - - // quiz savepoint reached - upgrade_mod_savepoint(true, 2011051229, 'quiz'); - } - - // Moodle v2.1.0 release upgrade line - // Put any upgrade step following this - - if ($oldversion < 2011100600) { - - // Define field browsersecurity to be added to quiz - $table = new xmldb_table('quiz'); - $field = new xmldb_field('browsersecurity', XMLDB_TYPE_CHAR, '32', null, - XMLDB_NOTNULL, null, '[unknownvalue]', 'subnet'); - - // Conditionally launch add field browsersecurity - if (!$dbman->field_exists($table, $field)) { - $dbman->add_field($table, $field); - } - - // quiz savepoint reached - upgrade_mod_savepoint(true, 2011100600, 'quiz'); - } - - if ($oldversion < 2011100601) { - $DB->set_field('quiz', 'browsersecurity', '-', array('popup' => 0)); - $DB->set_field('quiz', 'browsersecurity', 'securewindow', array('popup' => 1)); - $DB->set_field('quiz', 'browsersecurity', 'safebrowser', array('popup' => 2)); - - upgrade_mod_savepoint(true, 2011100601, 'quiz'); - } - - if ($oldversion < 2011100602) { - - // Changing the default of field browsersecurity on table quiz to drop it - $table = new xmldb_table('quiz'); - $field = new xmldb_field('browsersecurity', XMLDB_TYPE_CHAR, '32', null, - XMLDB_NOTNULL, null, null, 'subnet'); - - // Launch change of default for field browsersecurity - $dbman->change_field_default($table, $field); - - // quiz savepoint reached - upgrade_mod_savepoint(true, 2011100602, 'quiz'); - } - - if ($oldversion < 2011100603) { - - // Define field popup to be dropped from quiz - $table = new xmldb_table('quiz'); - $field = new xmldb_field('popup'); - - // Conditionally launch drop field popup - if ($dbman->field_exists($table, $field)) { - $dbman->drop_field($table, $field); - } - - // quiz savepoint reached - upgrade_mod_savepoint(true, 2011100603, 'quiz'); - } - - if ($oldversion < 2011100604) { - switch (get_config('quiz', 'popup')) { - case 1: - set_config('browsersecurity', 'securewindow', 'quiz'); - break; - case 2: - set_config('browsersecurity', 'safebrowser', 'quiz'); - break; - default: - set_config('browsersecurity', '-', 'quiz'); - } - unset_config('quiz', 'popup'); - - set_config('browsersecurity_adv', get_config('quiz', 'popup_adv'), 'quiz'); - unset_config('quiz', 'popup_adv'); - - upgrade_mod_savepoint(true, 2011100604, 'quiz'); - } // Moodle v2.2.0 release upgrade line // Put any upgrade step following this diff --git a/mod/quiz/db/upgradelib.php b/mod/quiz/db/upgradelib.php deleted file mode 100644 index ff2d00eda40..00000000000 --- a/mod/quiz/db/upgradelib.php +++ /dev/null @@ -1,94 +0,0 @@ -. - -/** - * Upgrade helper code for the quiz module. - * - * @package mod - * @subpackage quiz - * @copyright 2006 Eloy Lafuente (stronk7) - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ - - -defined('MOODLE_INTERNAL') || die(); - -require_once($CFG->dirroot . '/mod/quiz/locallib.php'); - - -/** - * Upgrade states for an attempt to Moodle 1.5 model - * - * Any state that does not yet have its timestamp set to nonzero has not yet been - * upgraded from Moodle 1.4. The reason these are still around is that for large - * sites it would have taken too long to upgrade all states at once. This function - * sets the timestamp field and creates an entry in the question_sessions table. - * @param object $attempt The attempt whose states need upgrading - */ -function quiz_upgrade_very_old_question_sessions($attempt) { - global $DB; - // The old quiz model only allowed a single response per quiz attempt so that there will be - // only one state record per question for this attempt. - - // We set the timestamp of all states to the timemodified field of the attempt. - $DB->execute("UPDATE {question_states} SET timestamp = ? WHERE attempt = ?", - array($attempt->timemodified, $attempt->uniqueid)); - - // For each state we create an entry in the question_sessions table, with both newest and - // newgraded pointing to this state. - // Actually we only do this for states whose question is actually listed in $attempt->layout. - // We do not do it for states associated to wrapped questions like for example the questions - // used by a random question - $session = new stdClass(); - $session->attemptid = $attempt->uniqueid; - $session->sumpenalty = 0; - $session->manualcomment = ''; - $session->manualcommentformat = FORMAT_HTML; - $session->flagged = 0; - - $questionlist = str_replace(',0', '', quiz_clean_layout($attempt->layout, true)); - if (!$questionlist) { - return; - } - list($usql, $question_params) = $DB->get_in_or_equal(explode(',', $questionlist)); - $params = array_merge(array($attempt->uniqueid), $question_params); - - if ($states = $DB->get_records_select('question_states', - "attempt = ? AND question $usql", $params)) { - foreach ($states as $state) { - if ($DB->record_exists('question_sessions', - array('attemptid' => $attempt->uniqueid, 'questionid' => $state->question))) { - // It was possible for the code to get here when some of the necessary - // question_sessions were already in the database. That lead to a - // unique key violation, so we manually detect and avoid that. - continue; - } - $session->newgraded = $state->id; - $session->newest = $state->id; - $session->questionid = $state->question; - $DB->insert_record('question_sessions', $session, false); - } - } - - // It was possible to have old question_states records for this attempt but - // pointing to questionids that were no longer in quiz_attempt->layout. - // That makes no sense, and will break things later in the upgrade, so delete - // those now. - list($qidsql, $params) = $DB->get_in_or_equal(explode(',', $questionlist), - SQL_PARAMS_QM, 'param', false); - $params[] = $attempt->uniqueid; - $DB->delete_records_select('question_states', "question $usql AND attempt = ?", $params); -} diff --git a/mod/resource/db/upgrade.php b/mod/resource/db/upgrade.php index 1a9d2bedc48..fc6245ed1ec 100644 --- a/mod/resource/db/upgrade.php +++ b/mod/resource/db/upgrade.php @@ -48,222 +48,9 @@ defined('MOODLE_INTERNAL') || die; function xmldb_resource_upgrade($oldversion) { global $CFG, $DB; - require_once("$CFG->dirroot/mod/resource/db/upgradelib.php"); $dbman = $DB->get_manager(); -//===== 1.9.0 upgrade line ======// - - if ($oldversion < 2009041900) { - resource_20_prepare_migration(); - // resource savepoint reached - upgrade_mod_savepoint(true, 2009041900, 'resource'); - } - - if ($oldversion < 2009042000) { - // Rename field summary on table resource to intro - $table = new xmldb_table('resource'); - $field = new xmldb_field('summary', XMLDB_TYPE_TEXT, 'small', null, null, null, null, 'reference'); - - // Launch rename field summary - $dbman->rename_field($table, $field, 'intro'); - - // resource savepoint reached - upgrade_mod_savepoint(true, 2009042000, 'resource'); - } - - if ($oldversion < 2009042001) { - // Define field introformat to be added to resource - $table = new xmldb_table('resource'); - $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('resource', array('introformat'=>FORMAT_MOODLE), '', 'id,intro,introformat'); - foreach ($rs as $r) { - $r->intro = text_to_html($r->intro, false, false, true); - $r->introformat = FORMAT_HTML; - $DB->update_record('resource', $r); - upgrade_set_timeout(); - } - $rs->close(); - } - - // resource savepoint reached - upgrade_mod_savepoint(true, 2009042001, 'resource'); - } - - if ($oldversion < 2009062600) { - $res_count = $DB->count_records('resource'); - $old_count = $DB->count_records('resource_old', array('migrated'=>0)); - if ($res_count != $old_count) { - //we can not continue, something is very wrong!! - upgrade_log(UPGRADE_LOG_ERROR, null, 'Resource migration failed.'); - upgrade_mod_savepoint(false, 2009062600, 'resource'); - } - - // Drop obsoleted fields from resource table - $table = new xmldb_table('resource'); - $fields = array('type', 'reference', 'alltext', 'popup', 'options'); - foreach ($fields as $fname) { - $field = new xmldb_field($fname); - $dbman->drop_field($table, $field); - } - - // resource savepoint reached - upgrade_mod_savepoint(true, 2009062600, 'resource'); - } - - if ($oldversion < 2009062601) { - $table = new xmldb_table('resource'); - // Define field tobemigrated to be added to resource - $field = new xmldb_field('tobemigrated', XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'introformat'); - // Conditionally launch add field tobemigrated - if (!$dbman->field_exists($table, $field)) { - $dbman->add_field($table, $field); - } - // Define field mainfile to be added to resource - $field = new xmldb_field('mainfile', XMLDB_TYPE_CHAR, '255', null, null, null, null, 'tobemigrated'); - // Conditionally launch add field mainfile - if (!$dbman->field_exists($table, $field)) { - $dbman->add_field($table, $field); - } - // Define field legacyfiles to be added to resource - $field = new xmldb_field('legacyfiles', XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'mainfile'); - // Conditionally launch add field legacyfiles - if (!$dbman->field_exists($table, $field)) { - $dbman->add_field($table, $field); - } - // Define field legacyfileslast to be added to resource - $field = new xmldb_field('legacyfileslast', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, 'legacyfiles'); - // Conditionally launch add field legacyfileslast - if (!$dbman->field_exists($table, $field)) { - $dbman->add_field($table, $field); - } - // Define field display to be added to resource - $field = new xmldb_field('display', XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'legacyfileslast'); - // Conditionally launch add field display - if (!$dbman->field_exists($table, $field)) { - $dbman->add_field($table, $field); - } - // Define field displayoptions to be added to resource - $field = new xmldb_field('displayoptions', XMLDB_TYPE_TEXT, 'small', null, null, null, null, 'display'); - // Conditionally launch add field displayoptions - if (!$dbman->field_exists($table, $field)) { - $dbman->add_field($table, $field); - } - // Define field filterfiles to be added to resource - $field = new xmldb_field('filterfiles', XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'displayoptions'); - // Conditionally launch add field filterfiles - if (!$dbman->field_exists($table, $field)) { - $dbman->add_field($table, $field); - } - // Define field revision to be added to resource - $field = new xmldb_field('revision', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'filterfiles'); - // Conditionally launch add field revision - if (!$dbman->field_exists($table, $field)) { - $dbman->add_field($table, $field); - } - - //mark all records as awaiting migration - $DB->set_field('resource', 'tobemigrated', 1, array()); - - // resource savepoint reached - upgrade_mod_savepoint(true, 2009062601, 'resource'); - } - - if ($oldversion < 2009062603) { - resource_20_migrate(); - upgrade_mod_savepoint(true, 2009062603, 'resource'); - } - - if ($oldversion < 2009063000) { - //migrate and prune old settings - admins need to review and set up all module settings anyway - if (!empty($CFG->resource_framesize)) { - set_config('framesize', $CFG->resource_framesize, 'resource'); - } - if (!empty($CFG->resource_popupheight)) { - set_config('popupheight', $CFG->resource_popupheight, 'resource'); - } - if (!empty($CFG->resource_popupwidth)) { - set_config('popupwidth', $CFG->resource_popupwidth, 'resource'); - } - - $cleanupsettings = array( - // migrated settings - 'resource_framesize', 'resource_popupheight', 'resource_popupwidth', 'resource_popupmenubar', - - // obsoleted settings - 'resource_websearch', 'resource_defaulturl', 'resource_allowlocalfiles', - 'resource_popup', 'resource_popupresizable', 'resource_popupscrollbars', - 'resource_popupdirectories', 'resource_popuplocation', - 'resource_popuptoolbar', 'resource_popupstatus', - - //waiting for some other modules or plugins to pick these up - /* - 'resource_secretphrase', - */ - ); - foreach ($cleanupsettings as $setting) { - unset_config($setting); - } - - upgrade_mod_savepoint(true, 2009063000, 'resource'); - } - - if ($oldversion < 2009080501) { - require_once("$CFG->libdir/filelib.php"); - - $sql = "SELECT r.id, - r.mainfile, - cm.id AS cmid - FROM {resource} r - JOIN {modules} m ON m.name='resource' - JOIN {course_modules} cm ON (cm.module = m.id AND cm.instance = r.id)"; - - $instances = $DB->get_recordset_sql($sql); - foreach ($instances as $instance) { - if (empty($instance->mainfile)) { - // weird - continue; - } - $context = get_context_instance(CONTEXT_MODULE, $instance->cmid, MUST_EXIST); - $parts = explode('/', $instance->mainfile); - $filename = array_pop($parts); - $filepath = implode('/', $parts); - file_set_sortorder($context->id, 'mod_resource', 'content', 0, $filepath, $filename, 1); - } - $instances->close(); - - /// Define field mainfile to be dropped from resource - $table = new xmldb_table('resource'); - $field = new xmldb_field('mainfile'); - $dbman->drop_field($table, $field); - - /// resource savepoint reached - upgrade_mod_savepoint(true, 2009080501, 'resource'); - } - - // MDL-10906. Removing resource_allowlocalfiles setting. - if ($oldversion < 2010083000) { - unset_config('resource_allowlocalfiles'); - upgrade_mod_savepoint(true, 2010083000, 'resource'); - } - - if ($oldversion < 2011022700) { - // refresh resource links breakage caused by invalid sortorder - require_once($CFG->dirroot . '/course/lib.php'); - rebuild_course_cache(0, true); - upgrade_mod_savepoint(true, 2011022700, 'resource'); - } - - // 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 diff --git a/mod/resource/db/upgradelib.php b/mod/resource/db/upgradelib.php deleted file mode 100644 index b8ec4e1f18c..00000000000 --- a/mod/resource/db/upgradelib.php +++ /dev/null @@ -1,304 +0,0 @@ -. - -/** - * Resource module upgrade related helper functions - * - * @package mod - * @subpackage resource - * @copyright 2009 Petr Skoda {@link http://skodak.org} - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ - -defined('MOODLE_INTERNAL') || die; - -/** - * Migrate resource module data from 1.9 resource_old table to new resource table - * @return void - */ -function resource_20_migrate() { - global $CFG, $DB; - - require_once("$CFG->libdir/filelib.php"); - require_once("$CFG->libdir/resourcelib.php"); - require_once("$CFG->dirroot/course/lib.php"); - - $fs = get_file_storage(); - - $withrelativelinks = array('text/html', 'text/xml', 'application/xhtml+xml', 'application/x-shockwave-flash'); - // note: pdf doc and other types may contain links too, but we do not support relative links there - - $candidates = $DB->get_recordset('resource_old', array('type'=>'file', 'migrated'=>0)); - if (!$candidates->valid()) { - $candidates->close(); // Not going to iterate (but exit), close rs - return; - } - - foreach ($candidates as $candidate) { - upgrade_set_timeout(); - - $path = $candidate->reference; - $siteid = get_site()->id; - $fs = get_file_storage(); - - if (empty($candidate->cmid)) { - // skip borked records - continue; - - } else if (strpos($path, 'LOCALPATH') === 0) { - // ignore not maintained local files - sorry - continue; - - } else if (preg_match("|$CFG->wwwroot/file.php(\?file=)?/$siteid(/[^\s'\"&\?#]+)|", $path, $matches)) { - // public site files - $path = $matches[2]; - - $resource = new stdClass(); - $resource->id = $candidate->oldid; - $resource->tobemigrated = 0; - $resource->mainfile = $path; - $resource->filterfiles = $CFG->filteruploadedfiles; - $resource->legacyfiles = RESOURCELIB_LEGACYFILES_NO; // on-demand-migration not possible for site files, sorry - - $context = get_context_instance(CONTEXT_MODULE, $candidate->cmid); - $sitecontext = get_context_instance(CONTEXT_COURSE, $siteid); - $file_record = array('contextid'=>$context->id, 'component'=>'mod_resourse', 'filearea'=>'content', 'itemid'=>0); - if ($file = $fs->get_file_by_hash(sha1("/$sitecontext->id/course/legacy/content/0".$path))) { - try { - $fs->create_file_from_storedfile($file_record, $file); - } catch (Exception $x) { - } - $resource->mainfile = $file->get_filepath().$file->get_filename(); - } - - } else if (preg_match("|$CFG->wwwroot/file.php(\?file=)?/$candidate->course(/[^\s'\"&\?#]+)|", $path, $matches)) { - // current course files - $path = $matches[2]; - - $resource = new stdClass(); - $resource->id = $candidate->oldid; - $resource->tobemigrated = 0; - $resource->mainfile = $path; - $resource->filterfiles = $CFG->filteruploadedfiles; - $mimetype = mimeinfo('type', $resource->mainfile); - if (in_array($mimetype, $withrelativelinks)) { - $resource->legacyfiles = RESOURCELIB_LEGACYFILES_ACTIVE; - } else { - $resource->legacyfiles = RESOURCELIB_LEGACYFILES_NO; - } - - // try migration of main file - ignore if does not exist - if ($file = resourcelib_try_file_migration($resource->mainfile, $candidate->cmid, $candidate->course, 'mod_resource', 'content', 0)) { - $resource->mainfile = $file->get_filepath().$file->get_filename(); - } - - } else if (strpos($path, '://') or strpos($path, '/') === 0) { - // http:// https:// ftp:// OR starts with slash - to be converted to link resource - continue; - - } else { - // current course files - // cleanup old path first - $path = '/'.trim(trim($path), '/'); - if (strpos($path, '?forcedownload=1') !== false) { - // eliminate old force download tricks - $candidate->options = 'forcedownload'; - $path = str_replace('?forcedownload=1', '', $path); - } - // get rid of any extra url parameters, sorry we can not support these - preg_match("/^[^?#]+/", $path, $matches); - $parts = $matches[0]; - - $resource = new stdClass(); - $resource->id = $candidate->oldid; - $resource->tobemigrated = 0; - $resource->mainfile = $path; - $resource->filterfiles = $CFG->filteruploadedfiles; - $mimetype = mimeinfo('type', $resource->mainfile); - if (in_array($mimetype, $withrelativelinks)) { - $resource->legacyfiles = RESOURCELIB_LEGACYFILES_ACTIVE; - } else { - $resource->legacyfiles = RESOURCELIB_LEGACYFILES_NO; - } - - // try migration of main file - ignore if does not exist - if ($file = resourcelib_try_file_migration($resource->mainfile, $candidate->cmid, $candidate->course, 'mod_resource', 'content', 0)) { - $resource->mainfile = $file->get_filepath().$file->get_filename(); - } - } - - $options = array('printheading'=>0, 'printintro'=>1); - if ($candidate->options == 'frame') { - $resource->display = RESOURCELIB_DISPLAY_FRAME; - - } else if ($candidate->options == 'objectframe') { - $resource->display = RESOURCELIB_DISPLAY_EMBED; - - } else if ($candidate->options == 'forcedownload') { - $resource->display = RESOURCELIB_DISPLAY_DOWNLOAD; - - } else if ($candidate->popup) { - $resource->display = RESOURCELIB_DISPLAY_POPUP; - if ($candidate->popup) { - $rawoptions = explode(',', $candidate->popup); - foreach ($rawoptions as $rawoption) { - list($name, $value) = explode('=', trim($rawoption), 2); - if ($value > 0 and ($name == 'width' or $name == 'height')) { - $options['popup'.$name] = $value; - continue; - } - } - } - - } else { - $resource->display = RESOURCELIB_DISPLAY_AUTO; - } - $resource->displayoptions = serialize($options); - - // update resource instance and mark as migrated - $DB->update_record('resource', $resource); - $candidate->newmodule = 'resource'; - $candidate->newid = $candidate->oldid; - $candidate->migrated = time(); - $DB->update_record('resource_old', $candidate); - } - - $candidates->close(); - - // clear all course modinfo caches - rebuild_course_cache(0, true); -} - -/** - * This function creates resource_old table and copies all data - * from resource table, this functions has to be called from - * all modules that are successors of old resource module types. - * @return bool true if migration required, false if not - */ -function resource_20_prepare_migration() { - global $DB; - - $dbman = $DB->get_manager(); - - // If the resource not created yet, this is probably a new install - $table = new xmldb_table('resource'); - if (!$dbman->table_exists($table)) { - return false; - } - - // Define table resource_old to be created - $table = new xmldb_table('resource_old'); - - if ($dbman->table_exists($table)) { - //already executed - return true; - } - - // fix invalid NULL popup and options data in old mysql databases - $sql = "UPDATE {resource} SET popup = ? WHERE popup IS NULL"; - $DB->execute($sql, array($DB->sql_empty())); - $sql = "UPDATE {resource} SET options = ? WHERE options IS NULL"; - $DB->execute($sql, array($DB->sql_empty())); - - // Adding fields to table resource_old - $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); - $table->add_field('course', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); - $table->add_field('name', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null); - $table->add_field('type', XMLDB_TYPE_CHAR, '30', null, XMLDB_NOTNULL, null, null); - $table->add_field('reference', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null); - $table->add_field('intro', XMLDB_TYPE_TEXT, 'small', null, null, null, null); - $table->add_field('introformat', XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); - $table->add_field('alltext', XMLDB_TYPE_TEXT, 'medium', null, XMLDB_NOTNULL, null, null); - $table->add_field('popup', XMLDB_TYPE_TEXT, 'small', null, XMLDB_NOTNULL, null, null); - $table->add_field('options', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null); - $table->add_field('timemodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); - $table->add_field('oldid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null); - $table->add_field('cmid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null); - $table->add_field('newmodule', XMLDB_TYPE_CHAR, '50', null, null, null, null); - $table->add_field('newid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null); - $table->add_field('migrated', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); - - // Adding keys to table resource_old - $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); - - // Adding indexes to table resource_old - $table->add_index('oldid', XMLDB_INDEX_UNIQUE, array('oldid')); - $table->add_index('cmid', XMLDB_INDEX_NOTUNIQUE, array('cmid')); - - // Launch create table for resource_old - $dbman->create_table($table); - - $module = $DB->get_field('modules', 'id', array('name'=>'resource')); - - if (!$DB->count_records('resource')) { - // upgrade of fresh new server from 1.9 - no upgrade needed - return false; - } - - // copy old data, the intro text format was FORMAT_MOODLE==0 - $sql = "INSERT INTO {resource_old} (oldid, course, name, type, reference, intro, introformat, alltext, popup, options, timemodified, cmid) - SELECT r.id, r.course, r.name, r.type, r.reference, r.summary, 0, r.alltext, r.popup, r.options, r.timemodified, cm.id - FROM {resource} r - LEFT JOIN {course_modules} cm ON (r.id = cm.instance AND cm.module = :module)"; - - $DB->execute($sql, array('module'=>$module)); - - return true; -} - -/** - * Migrate old resource type to new module, updates all related info, keeps the context id. - * @param string $modname name of new module - * @param object $candidate old instance from resource_old - * @param object $newinstance new module instance to be inserted into db - * @return mixed false if error, object new instance with id if success - */ -function resource_migrate_to_module($modname, $candidate, $newinstance) { - global $DB; - - if (!$cm = get_coursemodule_from_id('resource', $candidate->cmid)) { - return false; - } - - if (!$module = $DB->get_record('modules', array('name'=>$modname))) { - return false; - } - - if (!$resource = $DB->get_record('resource', array('id'=>$candidate->oldid))) { - return false; - } - - // insert new instance - $newinstance->id = $DB->insert_record($modname, $newinstance); - - // update course modules - $cm->module = $module->id; - $cm->instance = $newinstance->id; - $DB->update_record('course_modules', $cm); - - //delete old record - $DB->delete_records('resource', array('id'=>$resource->id)); - - //mark as migrated - $candidate->newmodule = $modname; - $candidate->newid = $newinstance->id; - $candidate->migrated = time(); - $DB->update_record('resource_old', $candidate); - - //no need to upgrade data in logs because resource module is able to redirect to migrated instances - return $newinstance; -} diff --git a/mod/scorm/db/upgrade.php b/mod/scorm/db/upgrade.php index c48eaeb0ec2..7f2bb3a349c 100644 --- a/mod/scorm/db/upgrade.php +++ b/mod/scorm/db/upgrade.php @@ -34,575 +34,6 @@ function xmldb_scorm_upgrade($oldversion) { $dbman = $DB->get_manager(); -//===== 1.9.0 upgrade line ======// - - // Adding missing 'whatgrade' field to table scorm - if ($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); - $whatgradefixed = get_config('scorm', 'whatgradefixed'); - if (empty($whatgradefixed)) { - /// fix bad usage of whatgrade/grading method. - $scorms = $DB->get_records('scorm'); - foreach ($scorms as $scorm) { - $scorm->whatgrade = $scorm->grademethod/10; - $DB->update_record('scorm', $scorm); - } - } - } else { - //dump this config var as it isn't needed anymore. - unset_config('whatgradefixed', 'scorm'); - } - - upgrade_mod_savepoint(true, 2008073000, 'scorm'); - } - - if ($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(true, 2008082500, 'scorm'); - } - - if ($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(true, 2008090300, 'scorm'); - } - - if ($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(true, 2008090301, 'scorm'); - } - - if ($oldversion < 2008090302) { - $sql = "UPDATE {scorm} - SET scormtype = 'external' - 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} - SET scormtype = 'localsync' - WHERE reference LIKE ? OR reference LIKE ? OR reference LIKE ? - 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(true, 2008090302, 'scorm'); - } - - if ($oldversion < 2008090303) { - //remove obsoleted config settings - unset_config('scorm_advancedsettings'); - unset_config('scorm_windowsettings'); - - /// scorm savepoint reached - upgrade_mod_savepoint(true, 2008090303, 'scorm'); - } - - if ($oldversion < 2008090304) { - ///////////////////////////////////// - /// new file storage upgrade code /// - ///////////////////////////////////// - - require_once("$CFG->dirroot/mod/scorm/db/upgradelib.php"); - - $fs = get_file_storage(); - - $sqlfrom = "FROM {scorm} s - JOIN {modules} m ON m.name = 'scorm' - JOIN {course_modules} cm ON (cm.module = m.id AND cm.instance = s.id)"; - - $count = $DB->count_records_sql("SELECT COUNT('x') $sqlfrom"); - - $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"); - if ($rs->valid()) { - - $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); - - if ($scorm->scormtype === 'local' and preg_match('/.*(\.zip|\.pif)$/i', $scorm->reference)) { - // first copy local packages if found - do not delete in case they are shared ;-) - $packagefile = clean_param($scorm->reference, PARAM_PATH); - $pathnamehash = sha1("/$coursecontext->id/course/legacy/0/$packagefile"); - if ($file = $fs->get_file_by_hash($pathnamehash)) { - $file_record = array('contextid'=>$context->id, 'component'=>'mod_scorm', 'filearea'=>'package', - 'itemid'=>0, 'filepath'=>'/'); - try { - $fs->create_file_from_storedfile($file_record, $file); - } catch (Exception $x) { - // ignore any errors, we can not do much anyway - } - $scorm->reference = $file->get_filepath().$file->get_filename(); - - } else { - $scorm->reference = ''; - } - $DB->update_record('scorm', $scorm); - // the package should be already extracted, we need to move the files there - // just in case somebody modified it directly there - scorm_migrate_moddata_files($scorm, $context); - - } else if ($scorm->scormtype === 'local' and preg_match('/.*\/imsmanifest\.xml$/i', $scorm->reference)) { - // ignore imsmanifest in course root because we would be duplicating all course files which is not acceptable - // moddata dir is not used at all, ignore any rubbish there - $manifest = clean_param($scorm->reference, PARAM_PATH); - - $pathnamehash = sha1("/$coursecontext->id/course/legacy/0/$manifest"); - if ($file = $fs->get_file_by_hash($pathnamehash)) { - $scorm->reference = $file->get_filepath().$file->get_filename(); - - $manifestdir = '/'.str_ireplace('/imsmanifest.xml', '', $manifest).'/'; - $pregmanifestdir = preg_quote($manifestdir, '/'); - $file_record = array('contextid'=>$context->id, 'component'=>'mod_scorm', 'filearea'=>'content', 'itemid'=>0); - if ($files = $fs->get_directory_files($coursecontext->id, 'course', 'legacy', 0, $manifestdir, true)) { - foreach ($files as $file) { - $file_record['filepath'] = preg_replace("/^$pregmanifestdir/", '/', $file->get_filepath()); - try { - $fs->create_file_from_storedfile($file_record, $file); - } catch (Exception $x) { - // ignore any errors, we can not do much anyway - } - } - } - - } else { - $scorm->reference = ''; - } - $DB->update_record('scorm', $scorm); - - } else { - // just try to migrate anything from moddata - scorm_migrate_moddata_files($scorm, $context); - } - - // 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(true, 2008090304, 'scorm'); - } - - - if ($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, XMLDB_NOTNULL, null, 1, 'maxattempt'); - if (!$dbman->field_exists($table,$field)) { - $dbman->add_field($table, $field); - } - $field = new xmldb_field('forcenewattempt', XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, 0, 'forcecompleted'); - if (!$dbman->field_exists($table,$field)) { - $dbman->add_field($table, $field); - } - $field = new xmldb_field('lastattemptlock', XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, 0, 'forcenewattempt'); - if (!$dbman->field_exists($table,$field)) { - $dbman->add_field($table, $field); - } - $field = new xmldb_field('displayattemptstatus', XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, 1, 'lastattemptlock'); - if (!$dbman->field_exists($table,$field)) { - $dbman->add_field($table, $field); - } - $field = new xmldb_field('displaycoursestructure', XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, 1, 'displayattemptstatus'); - if (!$dbman->field_exists($table,$field)) { - $dbman->add_field($table, $field); - } - - /// scorm savepoint reached - upgrade_mod_savepoint(true, 2008090305, 'scorm'); - } - - - // remove redundant config values - if ($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(true, 2008090306, 'scorm'); - } - - - - // remove redundant config values - if ($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(true, 2008090307, 'scorm'); - } - - if ($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(true, 2008090308, 'scorm'); - } - - - if ($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); - set_config($shortname, $CFG->$rcfg, 'scorm'); - unset_config($rcfg); - } - } - - /// scorm savepoint reached - upgrade_mod_savepoint(true, 2008090310, 'scorm'); - } - - if ($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(true, 2009042000, 'scorm'); - } - - if ($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 - 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('scorm', array('introformat'=>FORMAT_MOODLE), '', 'id,intro,introformat'); - foreach ($rs as $s) { - $s->intro = text_to_html($s->intro, false, false, true); - $s->introformat = FORMAT_HTML; - $DB->update_record('scorm', $s); - upgrade_set_timeout(); - } - $rs->close(); - } - - /// scorm savepoint reached - upgrade_mod_savepoint(true, 2009042001, 'scorm'); - } - - if ($oldversion < 2009042002) { - - /// Define field introformat to be added to scorm - $table = new xmldb_table('scorm_scoes'); - $field = new xmldb_field('launch', XMLDB_TYPE_TEXT, 'small', null, XMLDB_NOTNULL, null, null); - - /// Launch add field introformat - $dbman->change_field_type($table, $field); - - /// scorm savepoint reached - upgrade_mod_savepoint(true, 2009042002, 'scorm'); - } - if ($oldversion < 2010070800) { - //check to see if this has already been tidied up by a 1.9 upgrade. - $grademethodfixed = get_config('scorm', 'grademethodfixed'); - if (empty($grademethodfixed)) { - /// fix bad usage of whatgrade/grading method. - $scorms = $DB->get_records('scorm'); - if (!empty($scorm)) { - foreach ($scorms as $scorm) { - $scorm->grademethod = $scorm->grademethod%10; - $DB->update_record('scorm', $scorm); - } - } - } else { - //dump this config var as it isn't needed anymore. - unset_config('grademethodfixed', 'scorm'); - } - - /// scorm savepoint reached - upgrade_mod_savepoint(true, 2010070800, 'scorm'); - } - if ($oldversion < 2010092400) { - $count = $DB->count_records('scorm', array('scormtype'=>'external')); - if (!empty($count)) { - set_config('allowtypeexternal', '1', 'scorm'); - } - $count = $DB->count_records('scorm', array('scormtype'=>'localsync')); - if (!empty($count)) { - set_config('allowtypelocalsync', '1', 'scorm'); - } - $count = $DB->count_records('scorm', array('scormtype'=>'imsrepository')); - if (!empty($count)) { - set_config('allowtypeimsrepository', '1', 'scorm'); - } - /// scorm savepoint reached - upgrade_mod_savepoint(true, 2010092400, 'scorm'); - } - - if ($oldversion < 2011011400) { - // Fix scorm in the post table after upgrade from 1.9 - $table = new xmldb_table('scorm'); - $columns = $DB->get_columns('scorm'); - - // forcecompleted should be int(1) not null default 1 - // Changing to NOT NULL, let's fill the current nulls with default 1 - $DB->set_field('scorm', 'forcecompleted', 1, array('forcecompleted' => null)); - $field = new xmldb_field('forcecompleted', XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, 1, 'maxattempt'); - if ($dbman->field_exists($table, $field)) { - $dbman->change_field_precision($table, $field); - } - - if (array_key_exists('forcenewattempt', $columns) && empty($columns['forcenewattempt']->not_null)) { - // forcenewattempt should be int(1) not null default 0 - // Changing to NOT NULL, let's fill the current nulls with default 0 - $DB->set_field('scorm', 'forcenewattempt', 0, array('forcenewattempt' => null)); - $field = new xmldb_field('forcenewattempt', XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, 0, 'forcecompleted'); - if ($dbman->field_exists($table, $field)) { - $dbman->change_field_notnull($table, $field); - } - } - - if (array_key_exists('lastattemptlock', $columns) && empty($columns['lastattemptlock']->not_null)) { - // lastattemptlock should be int(1) not null default 0 - // Changing to NOT NULL, let's fill the current nulls with default 0 - $DB->set_field('scorm', 'lastattemptlock', 0, array('lastattemptlock' => null)); - $field = new xmldb_field('lastattemptlock', XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, 0, 'forcenewattempt'); - if ($dbman->field_exists($table, $field)) { - $dbman->change_field_notnull($table, $field); - } - } - - if (array_key_exists('displayattemptstatus', $columns) && empty($columns['displayattemptstatus']->not_null)) { - // displayattemptstatus should be int(1) not null default 1 - // Changing to NOT NULL, let's fill the current nulls with default 1 - $DB->set_field('scorm', 'displayattemptstatus', 1, array('displayattemptstatus' => null)); - $field = new xmldb_field('displayattemptstatus', XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, 1, 'lastattemptlock'); - if ($dbman->field_exists($table, $field)) { - $dbman->change_field_notnull($table, $field); - } - } - - if (array_key_exists('displaycoursestructure', $columns) && empty($columns['displaycoursestructure']->not_null)) { - // displaycoursestructure should be int(1) not null default 1 - // Changing to NOT NULL, let's fill the current nulls with default 1 - $DB->set_field('scorm', 'displaycoursestructure', 1, array('displaycoursestructure' => null)); - $field = new xmldb_field('displaycoursestructure', XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, 1, 'displayattemptstatus'); - if ($dbman->field_exists($table, $field)) { - $dbman->change_field_notnull($table, $field); - } - } - - upgrade_mod_savepoint(true, 2011011400, 'scorm'); - } - - // Moodle v2.1.0 release upgrade line - // Put any upgrade step following this - - if ($oldversion < 2011021402) { - unset_config('updatetime', 'scorm'); - upgrade_mod_savepoint(true, 2011021402, 'scorm'); - } - - if ($oldversion < 2011073100) { - // change field type of objectiveid - $table = new xmldb_table('scorm_seq_objective'); - $field = new xmldb_field('objectiveid', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, 'primaryobj'); - $dbman->change_field_type($table, $field); - upgrade_mod_savepoint(true, 2011073100, 'scorm'); - } - - if ($oldversion < 2011080100) { - //MDL-28295 the behaviour of pop-up windows has now changed - it now loads the full Player in the window - //because of this, pop-up windows now include the TOC and the nav bar - disabling these for existing SCORMS - //as it is a change that most users won't expect. - //get all SCORMS that use a new window. - require_once($CFG->dirroot."/mod/scorm/lib.php"); - $rs = $DB->get_recordset('scorm', array('popup' => 1), '', 'id,hidetoc,hidenav'); - foreach ($rs as $scorm) { - $scorm->hidetoc = SCORM_TOC_DISABLED; - $scorm->hidenav = 1; - $DB->update_record('scorm', $scorm); - } - $rs->close(); - - upgrade_mod_savepoint(true, 2011080100, 'scorm'); - } - if ($oldversion < 2011110502) { - - // Define table scorm_aicc_session to be created - $table = new xmldb_table('scorm_aicc_session'); - - // Adding fields to table scorm_aicc_session - $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); - $table->add_field('userid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); - $table->add_field('scormid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); - $table->add_field('hacpsession', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null); - $table->add_field('scoid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, '0'); - $table->add_field('scormmode', XMLDB_TYPE_CHAR, '50', null, null, null, null); - $table->add_field('scormstatus', XMLDB_TYPE_CHAR, '255', null, null, null, null); - $table->add_field('attempt', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null); - $table->add_field('lessonstatus', XMLDB_TYPE_CHAR, '255', null, null, null, null); - $table->add_field('sessiontime', XMLDB_TYPE_CHAR, '255', null, null, null, null); - $table->add_field('timecreated', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); - $table->add_field('timemodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); - - // Adding keys to table scorm_aicc_session - $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); - $table->add_key('scormid', XMLDB_KEY_FOREIGN, array('scormid'), 'scorm', array('id')); - $table->add_key('userid', XMLDB_KEY_FOREIGN, array('userid'), 'user', array('id')); - - // Conditionally launch create table for scorm_aicc_session - if (!$dbman->table_exists($table)) { - $dbman->create_table($table); - } - - // scorm savepoint reached - upgrade_mod_savepoint(true, 2011110502, 'scorm'); - } // Moodle v2.2.0 release upgrade line // Put any upgrade step following this diff --git a/mod/scorm/db/upgradelib.php b/mod/scorm/db/upgradelib.php deleted file mode 100644 index 3df00bc90da..00000000000 --- a/mod/scorm/db/upgradelib.php +++ /dev/null @@ -1,109 +0,0 @@ -. - -/** - * Resource module upgrade related helper functions - * - * @package mod - * @subpackage scorm - * @copyright 2010 Petr Skoda {@link http://skodak.org} - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ - -defined('MOODLE_INTERNAL') || die; - -/** - * Migrate extracted scorm package from moddata to new area if found - * @param stdClass $scorm - * @return - */ -function scorm_migrate_moddata_files($scorm, $context) { - global $CFG; - - // now migrate the extracted package - $basepath = "$CFG->dataroot/$scorm->course/$CFG->moddata/scorm/$scorm->id"; - if (!is_dir($basepath)) { - //no files? - return; - } - - scorm_migrate_moddata_subdir($context, $basepath, '/'); -} -/** - * Migrates physical scorm package files to proper new file area files - * @param stdClass $context - * @param string $base - * @param string $path - * @return void - */ -function scorm_migrate_moddata_subdir($context, $base, $path) { - global $OUTPUT; - - $fullpathname = $base.$path; - $fs = get_file_storage(); - $filearea = '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, 'mod_scorm', $filearea, '0', $filepath, $filename)) { - $file_record = array('contextid'=>$context->id, 'component'=>'mod_scorm', '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_moddata_subdir($context, $base, $subpath); - @rmdir($oldpathname); // deletes dir if empty - } - } - unset($items); //release file handles -} diff --git a/mod/survey/db/upgrade.php b/mod/survey/db/upgrade.php index ab5b273ff63..3a10f2827b5 100644 --- a/mod/survey/db/upgrade.php +++ b/mod/survey/db/upgrade.php @@ -25,37 +25,6 @@ function xmldb_survey_upgrade($oldversion) { $dbman = $DB->get_manager(); -//===== 1.9.0 upgrade line ======// - - if ($oldversion < 2009042002) { - - /// Define field introformat to be added to survey - $table = new xmldb_table('survey'); - $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('survey', array('introformat'=>FORMAT_MOODLE), '', 'id,intro,introformat'); - foreach ($rs as $s) { - $s->intro = text_to_html($s->intro, false, false, true); - $s->introformat = FORMAT_HTML; - $DB->update_record('survey', $s); - upgrade_set_timeout(); - } - $rs->close(); - } - - /// survey savepoint reached - upgrade_mod_savepoint(true, 2009042002, 'survey'); - } - - // 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 diff --git a/mod/url/db/install.php b/mod/url/db/install.php index 90de4aabb67..83eb420f928 100644 --- a/mod/url/db/install.php +++ b/mod/url/db/install.php @@ -34,21 +34,4 @@ defined('MOODLE_INTERNAL') || die; function xmldb_url_install() { global $CFG; - // migrate settings if present - if (!empty($CFG->resource_secretphrase)) { - set_config('secretphrase', $CFG->resource_secretphrase, 'url'); - } - unset_config('resource_secretphrase'); - - // Upgrade from old resource module type if needed - require_once("$CFG->dirroot/mod/url/db/upgradelib.php"); - url_20_migrate(); -} - -function xmldb_url_install_recovery() { - global $CFG; - - // Upgrade from old resource module type if needed - require_once("$CFG->dirroot/mod/url/db/upgradelib.php"); - url_20_migrate(); } diff --git a/mod/url/db/upgrade.php b/mod/url/db/upgrade.php index c636b674c12..88e0ba05827 100644 --- a/mod/url/db/upgrade.php +++ b/mod/url/db/upgrade.php @@ -51,22 +51,6 @@ function xmldb_url_upgrade($oldversion) { $dbman = $DB->get_manager(); - // Moodle v2.1.0 release upgrade line - // Put any upgrade step following this - if ($oldversion < 2011092800) { - - // Changing nullability of field externalurl on table urls to not-null - $table = new xmldb_table('url'); - $field = new xmldb_field('externalurl', XMLDB_TYPE_TEXT, 'small', null, - XMLDB_NOTNULL, null, null, 'introformat'); - - $DB->set_field_select('url', 'externalurl', $DB->sql_empty(), 'externalurl IS NULL'); - // Launch change of nullability for field =externalurl - $dbman->change_field_notnull($table, $field); - - // url savepoint reached - upgrade_mod_savepoint(true, 2011092800, 'url'); - } // Moodle v2.2.0 release upgrade line // Put any upgrade step following this diff --git a/mod/url/db/upgradelib.php b/mod/url/db/upgradelib.php deleted file mode 100644 index 8478fafd118..00000000000 --- a/mod/url/db/upgradelib.php +++ /dev/null @@ -1,140 +0,0 @@ -. - -/** - * URL module upgrade related helper functions - * - * @package mod - * @subpackage url - * @copyright 2009 Petr Skoda {@link http://skodak.org} - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ - -defined('MOODLE_INTERNAL') || die; - -/** - * Migrate url module data from 1.9 resource_old table to new url table - * @return void - */ -function url_20_migrate() { - global $CFG, $DB; - - require_once("$CFG->libdir/filelib.php"); - require_once("$CFG->libdir/resourcelib.php"); - require_once("$CFG->dirroot/course/lib.php"); - - if (!file_exists("$CFG->dirroot/mod/resource/db/upgradelib.php")) { - // bad luck, somebody deleted resource module - return; - } - - require_once("$CFG->dirroot/mod/resource/db/upgradelib.php"); - - // create resource_old table and copy resource table there if needed - if (!resource_20_prepare_migration()) { - // no modules or fresh install - return; - } - - $candidates = $DB->get_recordset('resource_old', array('type'=>'file', 'migrated'=>0)); - if (!$candidates->valid()) { - $candidates->close(); // Not going to iterate (but exit), close rs - return; - } - - foreach ($candidates as $candidate) { - $path = $candidate->reference; - $siteid = get_site()->id; - - if (strpos($path, 'LOCALPATH') === 0) { - // ignore not maintained local files - sorry - continue; - } else if (!strpos($path, '://')) { - // not URL - continue; - } else if (preg_match("|$CFG->wwwroot/file.php(\?file=)?/$siteid(/[^\s'\"&\?#]+)|", $path, $matches)) { - // handled by resource module - continue; - } else if (preg_match("|$CFG->wwwroot/file.php(\?file=)?/$candidate->course(/[^\s'\"&\?#]+)|", $path, $matches)) { - // handled by resource module - continue; - } - - upgrade_set_timeout(); - - if ($CFG->texteditors !== 'textarea') { - $intro = text_to_html($candidate->intro, false, false, true); - $introformat = FORMAT_HTML; - } else { - $intro = $candidate->intro; - $introformat = FORMAT_MOODLE; - } - - $url = new stdClass(); - $url->course = $candidate->course; - $url->name = $candidate->name; - $url->intro = $intro; - $url->introformat = $introformat; - $url->externalurl = $path; - $url->timemodified = time(); - - $options = array('printheading'=>0, 'printintro'=>1); - $parameters = array(); - if ($candidate->options == 'frame') { - $url->display = RESOURCELIB_DISPLAY_FRAME; - - } else if ($candidate->options == 'objectframe') { - $url->display = RESOURCELIB_DISPLAY_EMBED; - - } else if ($candidate->popup) { - $url->display = RESOURCELIB_DISPLAY_POPUP; - if ($candidate->popup) { - $rawoptions = explode(',', $candidate->popup); - foreach ($rawoptions as $rawoption) { - list($name, $value) = explode('=', trim($rawoption), 2); - if ($value > 0 and ($name == 'width' or $name == 'height')) { - $options['popup'.$name] = $value; - continue; - } - } - } - - } else { - $url->display = RESOURCELIB_DISPLAY_AUTO; - } - $url->displayoptions = serialize($options); - - if ($candidate->alltext) { - $rawoptions = explode(',', $candidate->alltext); - foreach ($rawoptions as $rawoption) { - list($variable, $parameter) = explode('=', trim($rawoption), 2); - $parameters[$parameter] = $variable; - } - } - - $url->parameters = serialize($parameters); - - if (!$url = resource_migrate_to_module('url', $candidate, $url)) { - continue; - } - } - - $candidates->close(); - - // clear all course modinfo caches - rebuild_course_cache(0, true); -} diff --git a/mod/wiki/db/install.php b/mod/wiki/db/install.php index bb58bd28fda..f88a91ef61d 100644 --- a/mod/wiki/db/install.php +++ b/mod/wiki/db/install.php @@ -3,6 +3,4 @@ function xmldb_wiki_install() { global $DB; - - } \ No newline at end of file diff --git a/mod/wiki/db/migration/lib.php b/mod/wiki/db/migration/lib.php deleted file mode 100644 index b65a3d5304d..00000000000 --- a/mod/wiki/db/migration/lib.php +++ /dev/null @@ -1,582 +0,0 @@ -disablecamelcase == 1); - - // Block of dinamic ewiki defines - wiki_set_define("EWIKI_NAME", $wiki_entry->pagename); - wiki_set_define("EWIKI_DEFAULT_LANG", current_language()); - if ($moodle_disable_camel_case) { - wiki_set_define("EWIKI_CHARS_L", ""); - wiki_set_define("EWIKI_CHARS_U", ""); - } else { - wiki_set_define("EWIKI_CHARS_L", "a-z_µ¤$\337-\377"); - wiki_set_define("EWIKI_CHARS_U", "A-Z0-9\300-\336"); - } - - wiki_set_define("EWIKI_CHARS", wiki_get_define('EWIKI_CHARS_L') . wiki_get_define('EWIKI_CHARS_U')); - - require_once($CFG->dirroot . '/mod/wiki/db/migration/wiki/ewikimoodlelib.php'); - require_once($CFG->dirroot . '/mod/wiki/db/migration/wiki/ewiki/ewiki.php'); - - if ($oldwiki->htmlmode == 0) { - # No HTML - $ewiki_config["htmlentities"] = array(); // HTML is managed by moodle - $moodle_format = FORMAT_TEXT; - } - if ($oldwiki->htmlmode == 1) { - # Safe HTML - include_once($CFG->dirroot . "/mod/wiki/db/migration/wiki/ewiki/plugins/moodle/moodle_rescue_html.php"); - $moodle_format = FORMAT_HTML; - } - if ($oldwiki->htmlmode == 2) { - # HTML Only - $moodle_format = FORMAT_HTML; - $ewiki_use_editor = 1; - $ewiki_config["htmlentities"] = array(); // HTML is allowed - $ewiki_config["wiki_link_regex"] = "\007 [!~]?( - \#?\[[^<>\[\]\n]+\] | - \^[-" . - wiki_get_define('EWIKI_CHARS_U') . wiki_get_define('EWIKI_CHARS_L') . "]{3,} | - \b([\w]{3,}:)*([" . - wiki_get_define('EWIKI_CHARS_U') . "]+[" . wiki_get_define('EWIKI_CHARS_L') . "]+){2,}\#?[\w\d]* | - \w[-_.+\w]+@(\w[-_\w]+[.])+\w{2,} ) \007x"; - } - - $content = ewiki_format($oldpage->content); - - return $content; -} - -function wiki_set_define($key, $value) { - global $ewikidefines; - - $ewikidefines[$key] = $value; -} - -function wiki_get_define($key) { - global $ewikidefines; - - return $ewikidefines[$key]; -} - -function ewiki_mime_magic($binary_data) { - $mime_magic_data = array( - array(0, 2, 0, "\x06\x02", "application/x-alan-adventure-game"), - array(0, 4, 0, "TADS", "application/x-tads-game"), - array(0, 2, 0, "\x01\x10", "application/x-executable-file"), - array(0, 2, 0, "\x01\x11", "application/x-executable-file"), - array(0, 2, 0, "\x01ƒ", "application/x-executable-file"), - array(0, 5, 0, "Core\001", "application/x-executable-file"), - array(0, 22, 0, "AMANDA: TAPESTART DATE", "application/x-amanda-header"), - array(0, 2, 0xfff0, 0xf0ff, "audio/mpeg"), - array(4, 2, 0, "¯\x11", "video/fli"), - array(4, 2, 0, "¯\x12", "video/flc"), - array(0, 4, 0, "MOVI", "video/x-sgi-movie"), - array(4, 4, 0, "moov", "video/quicktime"), - array(4, 4, 0, "mdat", "video/quicktime"), - array(0, 18, 0, "FiLeStArTfIlEsTaRt", "text/x-apple-binscii"), - array(0, 3, 0, "\x0aGL", "application/data"), - array(0, 2, 0, "\x76\xff", "application/data"), - array(0, 6, 0, "NuFile", "application/data"), - array(0, 6, 0, "N\xf5F\xe9l\xe5", "application/data"), - array(0, 4, 0, "\x00\x16\x05\x00", "application/data"), - array(0, 4, 0, "\x07\x16\x05\x00", "application/data"), - array(257, 6, 0, "ustar\0", "application/x-tar"), - array(257, 8, 0, "ustar\040\040\0", "application/x-gtar"), - array(0, 2, 0, "qÇ", "application/x-cpio"), - array(0, 2, 0, "Çq", "application/x-bcpio"), - array(0, 6, 0, "070707", "application/x-cpio"), - array(0, 6, 0, "070701", "application/x-cpio"), - array(0, 6, 0, "070702", "application/x-cpio"), - array(0, 2, 0, "ÿm", "application/data"), - array(0, 2, 0, "ÿe", "application/data"), - array(0, 5, 0, "=", "application/x-ar"), - array(0, 19, 0, "!\n__________E", "application/x-ar"), - array(0, 3, 0, "-h-", "application/data"), - array(0, 7, 0, "!", "application/x-ar"), - array(0, 4, 0, "", "application/x-ar"), - array(0, 4, 0, ">ra<", "application/x-ar"), - array(0, 4, 0, "!\n\n________64E", "application/data"), - array(0, 2, 0, "\x01ˆ", "application/x-executable-file"), - array(0, 2, 0, "\x01", "application/x-object-file"), - array(0, 3, 0, "\377\377\177", "application/data"), - array(0, 3, 0, "\377\377\174", "application/data"), - array(0, 3, 0, "\377\377\176", "application/data"), - array(0, 3, 0, "\033c\033", "application/data"), - array(0, 4, 0, "\x00\x12և", "image/x11"), - array(0, 8, 0, "!!\n", "application/x-prof"), - array(0, 2, 0, "\x05\x01", "application/x-locale"), - array(0, 4, 0, "\177ELF", "application/x-executable-file"), - array(0, 2, 0, "\x01T", "application/data"), - array(0, 2, 0, "\x01U", "application/x-executable-file"), - array(0x438, 2, 0, "ïS", "application/x-linux-ext2fs"), - array(0, 4, 0, "\366\366\366\366", "application/x-pc-floppy"), - array(0774, 2, 0, "¾Ú", "application/data"), - array(0x1FE, 2, 0, "ªU", "application/data"), - array(0x410, 2, 0, "\x13", "application/x-filesystem"), - array(0x410, 2, 0, "\x13", "application/x-filesystem"), - array(0x410, 2, 0, "\x24h", "application/x-filesystem"), - array(0x410, 2, 0, "\x24x", "application/x-filesystem"), - array(0, 9, 0, "-rom1fs-\0", "application/x-filesystem"), - array(0, 4, 0, "\x1b\x03\x136", "application/x-bootable"), - array(0x18b, 4, 0, "OS/2", "application/x-bootable"), - array(0, 4, 0, "FONT", "font/x-vfont"), - array(0, 2, 0, "\x01\x1e", "font/x-vfont"), - array(0, 2, 0, "\x1e\x01", "font/x-vfont"), - array(0, 18, 0, "%!PS-AdobeFont-1.0", "font/type1"), - array(6, 18, 0, "%!PS-AdobeFont-1.0", "font/type1"), - array(0, 10, 0, "STARTFONT\040", "font/x-bdf"), - array(0, 4, 0, "\001fcp", "font/x-pcf"), - array(0, 5, 0, "D1.0\015", "font/x-speedo"), - array(0, 3, 0, "flf", "font/x-figlet"), - array(0, 3, 0, "flc", "application/x-font"), - array(0, 4, 0, "\x19Y\x02\x14", "font/x-libgrx"), - array(0, 4, 0, "NOFÿ", "font/x-dos"), - array(7, 4, 0, "AGE\x00", "font/x-dos"), - array(7, 4, 0, "DIV\x00", "font/x-dos"), - array(0, 10, 0, "2', 2, 0, "º¾", "application/java"), - array(8, 4, 0, "AIFF", "audio/x-aiff"), - array(8, 4, 0, "AIFC", "audio/x-aiff"), - array(8, 4, 0, "8SVX", "audio/x-aiff"), - array('>8', 4, 0, "WAVE", "audio/x-wav"), - array('>8', 3, 0, "AVI", "video/x-msvideo"), - array(0, 3, 0, "ID3", "audio/mpeg"), - array(0, 4, 0, "OggS", "audio/x-ogg"), - array(0, 6, 0, "/* XPM", "image/x-xpm"), - array(16, 2, 0, "==", "image/x-3ds"), - array(0, 11, 0, "#!/bin/tcsh", "application/x-shellscript"), - array(0, 12, 0, "#! /bin/tcsh", "application/x-shellscript"), - array(0, 18, 0, "#! /usr/local/tcsh", "application/x-shellscript"), - array('>8', 6, 0, "debian", "application/x-debian-package"), - array('>2', 2, 0, "Ûî", "application/x-rpm"), - array(2, 5, 0, "-lh -", "application/x-lha"), - array(2, 5, 0, "-lh6-", "application/x-lha"), - array(2, 5, 0, "-lh7-", "application/x-lha"), - array(0, 15, 0, "8', 4, 0, "AVI ", "video/avi"), - array(0, 1, 0, "\x01", "video/unknown"), - array(0, 1, 0, "\x02", "video/unknown"), - array(0, 19, 0, "[KDE Desktop Entry]", "application/x-kdelnk"), - array(0, 18, 0, "\# KDE Config File", "application/x-kdelnk"), - array(0, 7, 0, "\# xmcd", "text/xmcd"), - array(0, 4, 0, "\x8aMNG", "video/x-mng"), - array(0, 4, 0, "ó\x03\x00\x00", "application/x-executable-file"), - array(0, 4, 0, "ç\x03\x00\x00", "application/x-library-file"), - array(0, 4, 0, "³\x01\x00\x00", "video/mpeg"), - array(0, 4, 0, "º\x01\x00\x00", "video/mpeg"), - array(0, 4, 0, "\x00\x00l", "application/x-apl-workspace"), - array(0, 4, 0, "\x00\x00ÿm", "application/x-ar"), - array(0, 4, 0, "\x00\x00ÿe", "application/data"), - array(0, 4, 0, "\x00\x00\x01\x06", "application/x-executable-file"), - array(0, 4, 0, "G\x01\x00\x00", "application/x-object-file"), - array(0, 4, 0, "K\x01\x00\x00", "application/x-executable-file"), - array(0, 4, 0, "M\x01\x00\x00", "application/x-executable-file"), - array(0, 4, 0, "O\x01\x00\x00", "application/x-executable-file"), - array(24, 4, 0, "kê\x00\x00", "application/data"), - array(24, 4, 0, "lê\x00\x00", "application/data"), - array(24, 4, 0, "mê\x00\x00", "application/data"), - array(24, 4, 0, "nê\x00\x00", "application/data"), - array(0, 4, 0, "\x01\x00\x00", "application/x-object-file"), - array(0, 4, 0, "‡\x01\x00\x00", "application/data"), - array(24, 4, 0, "\x00\x00êl", "application/x-dump"), - array(24, 4, 0, "\x00\x00êk", "application/x-dump"), - array(0, 4, 0, "\x00\x00¾1", "text/vnd.ms-word"), - array(0, 2, 0, "\x00\x00", "audio/mpeg"), - array('>16', 2, 0, "\x00\x01", "application/x-object"), - array('>16', 2, 0, "\x00\x02", "application/x-executable"), - array('>16', 2, 0, "\x00\x03", "application/x-sharedlib"), - array('>16', 2, 0, "\x00\x04", "application/x-coredump"), - array(0, 4, 0, "\x00\x00\x00Ì", "application/x-executable-file"), - array(0, 4, 0, "\x04\x00\x00\x00", "font/x-snf"), - array(0, 4, 0, "\x00\x00\x00\x04", "font/x-snf"), - array('>12', 4, 0, "\x01\x00\x00\x00", "audio/basic"), - array('>12', 4, 0, "\x02\x00\x00\x00", "audio/basic"), - array('>12', 4, 0, "\x03\x00\x00\x00", "audio/basic"), - array('>12', 4, 0, "\x04\x00\x00\x00", "audio/basic"), - array('>12', 4, 0, "\x05\x00\x00\x00", "audio/basic"), - array('>12', 4, 0, "\x06\x00\x00\x00", "audio/basic"), - array('>12', 4, 0, "\x07\x00\x00\x00", "audio/basic"), - array('>12', 4, 0, "\x17\x00\x00\x00", "audio/x-adpcm"), - array('>12', 4, 0, "\x00\x00\x00\x01", "audio/x-dec-basic"), - array('>12', 4, 0, "\x00\x00\x00\x02", "audio/x-dec-basic"), - array('>12', 4, 0, "\x00\x00\x00\x03", "audio/x-dec-basic"), - array('>12', 4, 0, "\x00\x00\x00\x04", "audio/x-dec-basic"), - array('>12', 4, 0, "\x00\x00\x00\x05", "audio/x-dec-basic"), - array('>12', 4, 0, "\x00\x00\x00\x06", "audio/x-dec-basic"), - array('>12', 4, 0, "\x00\x00\x00\x07", "audio/x-dec-basic"), - array('>12', 4, 0, "\x00\x00\x00\x17", "audio/x-dec-adpcm") - ); - - $fd = substr($binary_data, 0, 3072); - foreach ($mime_magic_data as $def) { - $pos0 = $def[0]; - if ($pos0[0] == ">") { - $pos0 = substr($pos0, 1); - if (@strpos($fd, $def[3], $pos0) !== false) { - return($def[4]); - } - } else { - $part = substr($fd, $pos0, $def[1]); - $mask = $def[2]; - if ($mask) { - // if $mask is 0 - $value = 1 * ('0x'.bin2hex($part)); - if (($value & $mask) == $def[3]) { - return($def[4]); - } - } else { - if ($part == $def[3]) { - return($def[4]); - } - } - } - } -} diff --git a/mod/wiki/db/migration/wiki/ewiki/ewiki.php b/mod/wiki/db/migration/wiki/ewiki/ewiki.php deleted file mode 100644 index 222385749fb..00000000000 --- a/mod/wiki/db/migration/wiki/ewiki/ewiki.php +++ /dev/null @@ -1,3626 +0,0 @@ - and many others(tm) - - - Use it from inside yoursite.php like that: - ... - - -*/ - -#-- you could also establish a mysql connection in here, of course: -// mysql_connect(":/var/run/mysqld/mysqld.sock", "user", "pw") -// and mysql_query("USE mydatabase"); - - - #-------------------------------------------------------- config --- - - #-- I'm sorry for that, but all the @ annoy me - error_reporting(0x0000377 & error_reporting()); -# error_reporting(E_ALL^E_NOTICE); - - #-- the position of your ewiki-wrapper script - define("EWIKI_SCRIPT", "?id="); # relative/absolute to docroot -# define("EWIKI_SCRIPT_URL", "http://...?id="); # absolute URL - - #-- change to your needs (site lang) - //define("EWIKI_NAME", "ErfurtWiki"); - define("EWIKI_PAGE_INDEX", "ErfurtWiki"); - define("EWIKI_PAGE_NEWEST", "NewestPages"); - define("EWIKI_PAGE_SEARCH", "SearchPages"); - define("EWIKI_PAGE_HITS", "MostVisitedPages"); - define("EWIKI_PAGE_VERSIONS", "MostOftenChangedPages"); - define("EWIKI_PAGE_UPDATES", "UpdatedPages"); - - #-- default settings are good settings - most often ;) - #- look & feel - define("EWIKI_PRINT_TITLE", 1); #

WikiPageName

on top - define("EWIKI_SPLIT_TITLE", 0); #

Wiki Page Name

- define("EWIKI_CONTROL_LINE", 1); # EditThisPage-link at bottom - define("EWIKI_LIST_LIMIT", 20); # listing limit - #- behaviour - define("EWIKI_AUTO_EDIT", 1); # edit box for non-existent pages - define("EWIKI_EDIT_REDIRECT", 1); # redirect after edit save - define("EWIKI_DEFAULT_ACTION", "view"); # (keep!) - define("EWIKI_CASE_INSENSITIVE", 1); # wikilink case sensitivity - define("EWIKI_HIT_COUNTING", 1); - define("UNIX_MILLENNIUM", 1000000000); - #- rendering - define("EWIKI_ALLOW_HTML", 0); # often a very bad idea - define("EWIKI_HTML_CHARS", 1); # allows for È - define("EWIKI_ESCAPE_AT", 1); # "@" -> "@" - #- http/urls - define("EWIKI_HTTP_HEADERS", 1); # most often a good thing - define("EWIKI_NO_CACHE", 1); # browser+proxy shall not cache - define("EWIKI_URLENCODE", 1); # disable when _USE_PATH_INFO - define("EWIKI_URLDECODE", 1); - define("EWIKI_USE_PATH_INFO", 1 &&!strstr($_SERVER["SERVER_SOFTWARE"],"Apache")); - define("EWIKI_USE_ACTION_PARAM", 1); - define("EWIKI_ACTION_SEP_CHAR", "/"); - define("EWIKI_UP_PAGENUM", "n"); # _UP_ means "url parameter" - define("EWIKI_UP_PAGEEND", "e"); - define("EWIKI_UP_BINARY", "binary"); - define("EWIKI_UP_UPLOAD", "upload"); - #- other stuff - //define("EWIKI_DEFAULT_LANG", "en"); - define("EWIKI_CHARSET", "UTF-8"); - #- user permissions - define("EWIKI_PROTECTED_MODE", 0); # disable funcs + require auth - define("EWIKI_PROTECTED_MODE_HIDING", 0); # hides disallowed actions - define("EWIKI_AUTH_DEFAULT_RING", 3); # 0=root 1=priv 2=user 3=view - define("EWIKI_AUTO_LOGIN", 1); # [auth_query] on startup - - #-- allowed WikiPageNameCharacters - -#### BEGIN MOODLE CHANGES - to remove auto-camelcase linking. -// global $moodle_disable_camel_case; -// if ($moodle_disable_camel_case) { -// define("EWIKI_CHARS_L", ""); -// define("EWIKI_CHARS_U", ""); -// } -// else { -//#### END MOODLE CHANGES -// -// define("EWIKI_CHARS_L", "a-z_µ¤$\337-\377"); -// define("EWIKI_CHARS_U", "A-Z0-9\300-\336"); -// -//#### BEGIN MOODLE CHANGES -// } -//#### END MOODLE CHANGES -// -// define("EWIKI_CHARS", EWIKI_CHARS_L.EWIKI_CHARS_U); -// -// COMMENTED BY PIGUI BECOUSE OF MIGRATION - - #-- database - define("EWIKI_DB_TABLE_NAME", "ewiki"); # MySQL / ADOdb - define("EWIKI_DBFILES_DIRECTORY", "/tmp"); # see "db_flat_files.php" - define("EWIKI_DBA", "/tmp/ewiki.dba"); # see "db_dba.php" - define("EWIKI_DBQUERY_BUFFER", 512*1024); # 512K - define("EWIKI_INIT_PAGES", "./init-pages"); # for initialization - - define("EWIKI_DB_F_TEXT", 1<<0); - define("EWIKI_DB_F_BINARY", 1<<1); - define("EWIKI_DB_F_DISABLED", 1<<2); - define("EWIKI_DB_F_HTML", 1<<3); - define("EWIKI_DB_F_READONLY", 1<<4); - define("EWIKI_DB_F_WRITEABLE", 1<<5); - define("EWIKI_DB_F_APPENDONLY", 1<<6); #nyi - define("EWIKI_DB_F_SYSTEM", 1<<7); - define("EWIKI_DB_F_PART", 1<<8); - define("EWIKI_DB_F_TYPE", EWIKI_DB_F_TEXT | EWIKI_DB_F_BINARY | EWIKI_DB_F_DISABLED | EWIKI_DB_F_SYSTEM | EWIKI_DB_F_PART); - define("EWIKI_DB_F_ACCESS", EWIKI_DB_F_READONLY | EWIKI_DB_F_WRITEABLE | EWIKI_DB_F_APPENDONLY); - define("EWIKI_DB_F_COPYMASK", EWIKI_DB_F_TYPE | EWIKI_DB_F_ACCESS); - - define("EWIKI_DBFILES_NLR", '\\n'); - define("EWIKI_DBFILES_ENCODE", 0 || (DIRECTORY_SEPARATOR != "/")); - define("EWIKI_DBFILES_GZLEVEL", "2"); - - #-- internal - define("EWIKI_ADDPARAMDELIM", (strstr(EWIKI_SCRIPT,"?") ? "&" : "?")); - - #-- binary content (images) - define("EWIKI_SCRIPT_BINARY", /*"/binary.php?binary="*/ ltrim(strtok(" ".EWIKI_SCRIPT,"?"))."?".EWIKI_UP_BINARY."=" ); - define("EWIKI_CACHE_IMAGES", 1 &&!headers_sent()); - define("EWIKI_IMAGE_MAXSIZE", 64 *1024); - define("EWIKI_IMAGE_MAXWIDTH", 3072); - define("EWIKI_IMAGE_MAXHEIGHT", 2048); - define("EWIKI_IMAGE_MAXALLOC", 1<<19); - define("EWIKI_IMAGE_RESIZE", 1); - define("EWIKI_IMAGE_ACCEPT", "image/jpeg,image/png,image/gif,application/x-shockwave-flash"); - define("EWIKI_IDF_INTERNAL", "internal://"); - define("EWIKI_ACCEPT_BINARY", 0); # for arbitrary binary data files - - #-- misc - define("EWIKI_TMP", $_SERVER["TEMP"] ? $_SERVER["TEMP"] : "/tmp"); - define("EWIKI_LOGLEVEL", -1); # 0=error 1=warn 2=info 3=debug - define("EWIKI_LOGFILE", "/tmp/ewiki.log"); - - #-- plugins (tasks mapped to function names) - $ewiki_plugins["database"][] = "ewiki_database_mysql"; - $ewiki_plugins["edit_preview"][] = "ewiki_page_edit_preview"; - $ewiki_plugins["render"][] = "ewiki_format"; - $ewiki_plugins["init"][-5] = "ewiki_localization"; - $ewiki_plugins["init"][-1] = "ewiki_binary"; - $ewiki_plugins["handler"][-105] = "ewiki_eventually_initialize"; - $ewiki_plugins["handler"][] = "ewiki_intermap_walking"; - $ewiki_plugins["view_append"][-1] = "ewiki_control_links"; - $ewiki_plugins["view_final"][-1] = "ewiki_add_title"; - $ewiki_plugins["page_final"][] = "ewiki_http_headers"; - $ewiki_plugins["page_final"][99115115] = "ewiki_page_css_container"; - $ewiki_plugins["edit_form_final"][] = "ewiki_page_edit_form_final_imgupload"; - $ewiki_plugins["format_block"]["pre"][] = "ewiki_format_pre"; - $ewiki_plugins["format_block"]["code"][] = "ewiki_format_pre"; - $ewiki_plugins["format_block"]["htm"][] = "ewiki_format_html"; - $ewiki_plugins["format_block"]["html"][] = "ewiki_format_html"; - $ewiki_plugins["format_block"]["comment"][] = "ewiki_format_comment"; - - - #-- internal pages - $ewiki_plugins["page"][EWIKI_PAGE_NEWEST] = "ewiki_page_newest"; - $ewiki_plugins["page"][EWIKI_PAGE_SEARCH] = "ewiki_page_search"; - if (EWIKI_HIT_COUNTING) $ewiki_plugins["page"][EWIKI_PAGE_HITS] = "ewiki_page_hits"; - $ewiki_plugins["page"][EWIKI_PAGE_VERSIONS] = "ewiki_page_versions"; - $ewiki_plugins["page"][EWIKI_PAGE_UPDATES] = "ewiki_page_updates"; - - #-- page actions - $ewiki_plugins["action"]["edit"] = "ewiki_page_edit"; - $ewiki_plugins["action_always"]["links"] = "ewiki_page_links"; - $ewiki_plugins["action"]["info"] = "ewiki_page_info"; - $ewiki_plugins["action"]["view"] = "ewiki_page_view"; - - #-- helper vars --------------------------------------------------- - $ewiki_config["idf"]["url"] = array("http://", "mailto:", "internal://", "ftp://", "https://", "irc://", "telnet://", "news://", "chrome://", "file://", "gopher://", "httpz://"); - $ewiki_config["idf"]["img"] = array(".jpeg", ".png", ".jpg", ".gif", ".j2k"); - $ewiki_config["idf"]["obj"] = array(".swf", ".svg"); - - #-- entitle actions - $ewiki_config["action_links"]["view"] = @array_merge(array( - "edit" => "EDITTHISPAGE", # ewiki_t() is called on these - "links" => "BACKLINKS", - "info" => "PAGEHISTORY", - "like" => "LIKEPAGES", - ), @$ewiki_config["action_links"]["view"] - ); - $ewiki_config["action_links"]["info"] = @array_merge(array( - "view" => "browse", - "edit" => "fetchback", - ), @$ewiki_config["action_links"]["info"] - ); - - #-- variable configuration settings (go into '$ewiki_config') - $ewiki_config_DEFAULTSTMP = array( - "edit_thank_you" => 1, - "edit_box_size" => "70x15", - "print_title" => EWIKI_PRINT_TITLE, - "split_title" => EWIKI_SPLIT_TITLE, - "control_line" => EWIKI_CONTROL_LINE, - "list_limit" => EWIKI_LIST_LIMIT, - "script" => EWIKI_SCRIPT, - "script_url" => (defined("EWIKI_SCRIPT_URL")?EWIKI_SCRIPT_URL:NULL), - "script_binary" => EWIKI_SCRIPT_BINARY, - #-- heart of the wiki -- don't try to read this! ;) - - "wiki_pre_scan_regex" => '/ - (? "\007 [!~]?( - \#?\[[^<>\[\]\n]+\] | - \^[-".wiki_get_define('EWIKI_CHARS_U').wiki_get_define('EWIKI_CHARS_L')."]{3,} | - \b([\w]{3,}:)*([".wiki_get_define('EWIKI_CHARS_U')."]+[".wiki_get_define('EWIKI_CHARS_L')."]+){2,}\#?[\w\d]* | - ([a-z]{2,9}://|mailto:)[^\s\[\]\'\"\)\,<]+ | - \w[-_.+\w]+@(\w[-_\w]+[.])+\w{2,} ) \007x", - - #-- rendering ruleset - "wm_indent" => '', - "wm_table_defaults" => 'cellpadding="2" border="1" cellspacing="0"', - "wm_whole_line" => array(), - "htmlentities" => array( - "&" => "&", - ">" => ">", - "<" => "<", - ), - "wm_source" => array( - "%%%" => "
", - "\t" => " ", - "\n;:" => "\n ", # workaround, replaces the old ;: - ), - "wm_list" => array( - "-" => array('ul type="square"', "", "li"), - "*" => array('ul type="circle"', "", "li"), - "#" => array("ol", "", "li"), - ":" => array("dl", "dt", "dd"), - ## ";" => array("dl", "dt", "dd"), - ), - "wm_style" => array( - "'''''" => array("", ""), - "'''" => array("", ""), - "___" => array("", ""), - "''" => array("", ""), - "__" => array("", ""), - "^^" => array("", ""), - "==" => array("", ""), - ## "***" => array("", ""), - ## "###" => array("", ""), - "**" => array("", ""), - "##" => array("", ""), - "µµ" => array("", ""), - ), - "wm_start_end" => array( - ), - #-- rendering plugins - "format_block" => array( - "html" => array("<html>", "</html>", "html", 0x0000), - "htm" => array("<htm>", "</htm>", "html", 0x0003), - "code" => array("<code>", "</code>", false, 0x0000), - "pre" => array("<pre>", "</pre>", false, 0x003F), - "comment" => array("\n<!--", "-->", false, 0x0030), - # "verbatim" => array("<verbatim>", "</verbatim>", false, 0x0000), - ), - "format_params" => array( - "scan_links" => 1, - "html" => EWIKI_ALLOW_HTML, - "mpi" => 1, - ), - ); - foreach ($ewiki_config_DEFAULTSTMP as $set => $val) { - if (!isset($ewiki_config[$set])) { - $ewiki_config[$set] = $val; - } - elseif (is_array($val)) foreach ($val as $vali=>$valv) { - if (is_int($vali)) { - $ewiki_config[$set][] = $valv; - } - elseif (!isset($ewiki_config[$set][$vali])) { - $ewiki_config[$set][$vali] = $valv; - } - } - } - $ewiki_config_DEFAULTSTMP = $valv = $vali = $val = NULL; - - #-- init stuff, autostarted parts - ksort($ewiki_plugins["init"]); - if ($pf_a = $ewiki_plugins["init"]) foreach ($pf_a as $pf) { - // Binary Handling starts here - #### MOODLE CHANGE TO BE COMPATIBLE WITH PHP 4.1 - #if(headers_sent($file,$line)) { - # print_error('headersent'); - /*if(headers_sent()) { - print_error('headersent'); - }*/ - $pf($GLOBALS); - } - unset($ewiki_plugins["init"]); - - #-- text (never remove the "C" or "en" sections!) - # - $ewiki_t["C"] = @array_merge(@$ewiki_t["C"], array( - "DATE" => "%a, %d %b %G %T %Z", - "EDIT_TEXTAREA_RESIZE_JS" => '+', - )); - # - $ewiki_t["en"] = @array_merge(@$ewiki_t["en"], array( - "EDITTHISPAGE" => "EditThisPage", - "APPENDTOPAGE" => "Add to", - "BACKLINKS" => "BackLinks", - "PAGESLINKINGTO" => "Pages linking to \$title", - "PAGEHISTORY" => "PageInfo", - "INFOABOUTPAGE" => "Information about page", - "LIKEPAGES" => "Pages like this", - "NEWESTPAGES" => "Newest Pages", - "LASTCHANGED" => "last changed on %c", - "DOESNOTEXIST" => "This page does not yet exist, please click on EditThisPage if you'd like to create it.", - "DISABLEDPAGE" => "This page is currently not available.", - "ERRVERSIONSAVE" => "Sorry, while you edited this page someone else - did already save a changed version. Please go back to the - previous screen and copy your changes to your computers - clipboard to insert it again after you reload the edit - screen.", - "ERRORSAVING" => "An error occoured while saving your changes. Please try again.", - "THANKSFORCONTRIBUTION" => "Thank you for your contribution!", - "CANNOTCHANGEPAGE" => "This page cannot be changed.", - "OLDVERCOMEBACK" => "Make this old version come back to replace the current one", - "PREVIEW" => "Preview", - "SAVE" => "Save", - "CANCEL_EDIT" => "CancelEditing", - "UPLOAD_PICTURE_BUTTON" => "upload picture >>>", - "EDIT_FORM_1" => "GoodStyle is to - write what comes to your mind. Don't care about how it - looks too much now. You can add WikiMarkup - also later if you think it is necessary.
", - "EDIT_FORM_2" => "
Please do not write things, which may make other - people angry. And please keep in mind that you are not all that - anonymous in the internet (find out more about your computers - 'IP address' at Google).", - "BIN_IMGTOOLARGE" => "Image file is too large!", - "BIN_NOIMG" => "This is no image file (inacceptable file format)!", - "FORBIDDEN" => "You are not authorized to access this page.", - )); - # - $ewiki_t["es"] = @array_merge(@$ewiki_t["es"], array( - "EDITTHISPAGE" => "EditarEstaPágina", - "BACKLINKS" => "EnlacesInversos", - "PAGESLINKINGTO" => "Páginas enlazando \$title", - "PAGEHISTORY" => "InfoPágina", - "INFOABOUTPAGE" => "Información sobre la página", - "LIKEPAGES" => "Páginas como esta", - "NEWESTPAGES" => "Páginas más nuevas", - "LASTCHANGED" => "última modificación %d/%m/%Y a las %H:%M", - "DOESNOTEXIST" => "Esta página aún no existe, por favor eliga EditarEstaPágina si desea crearla.", - "DISABLEDPAGE" => "Esta página no está disponible en este momento.", - "ERRVERSIONSAVE" => "Disculpe, mientras editaba esta página alguién más - salvó una versión modificada. Por favor regrese a - a la pantalla anterior y copie sus cambios a su computador - para insertalos nuevamente después de que cargue - la pantalla de edición.", - "ERRORSAVING" => "Ocurrió un error mientras se salvavan sus cambios. Por favor intente de nuevo.", - "THANKSFORCONTRIBUTION" => "Gracias por su contribución!", - "CANNOTCHANGEPAGE" => "Esta página no puede ser modificada.", - "OLDVERCOMEBACK" => "Hacer que esta versión antigua regrese a remplazar la actual", - "PREVIEW" => "Previsualizar", - "SAVE" => "Salvar", - "CANCEL_EDIT" => "CancelarEdición", - "UPLOAD_PICTURE_BUTTON" => "subir gráfica >>>", - "EDIT_FORM_1" => "BuenEstilo es - escribir lo que viene a su mente. No se preocupe mucho - por la apariencia. También puede agregar ReglasDeMarcadoWiki - más adelante si piensa que es necesario.
", - "EDIT_FORM_2" => "
Por favor no escriba cosas, que puedan - enfadar a otras personas. Y por favor tenga en mente que - usted no es del todo anónimo en Internet - (encuentre más sobre - 'IP address' de su computador con Google).", - "BIN_IMGTOOLARGE" => "¡La gráfica es demasiado grande!", - "BIN_NOIMG" => "¡No es un archivo con una gráfica (formato de archivo inaceptable)!", - "FORBIDDEN" => "No está autorizado para acceder a esta página.", - )); - # - $ewiki_t["de"] = @array_merge(@$ewiki_t["de"], array( - "EDITTHISPAGE" => "DieseSeiteÄndern", - "APPENDTOPAGE" => "Ergänze", - "BACKLINKS" => "ZurückLinks", - "PAGESLINKINGTO" => "Verweise zur Seite \$title", - "PAGEHISTORY" => "SeitenInfo", - "INFOABOUTPAGE" => "Informationen über Seite", - "LIKEPAGES" => "Ähnliche Seiten", - "NEWESTPAGES" => "Neueste Seiten", - "LASTCHANGED" => "zuletzt geändert am %d.%m.%Y um %H:%M", - "DISABLEDPAGE" => "Diese Seite kann momentan nicht angezeigt werden.", - "ERRVERSIONSAVE" => "Entschuldige, aber während Du an der Seite - gearbeitet hast, hat bereits jemand anders eine geänderte - Fassung gespeichert. Damit nichts verloren geht, browse bitte - zurück und speichere Deine Änderungen in der Zwischenablage - (Bearbeiten->Kopieren) um sie dann wieder an der richtigen - Stelle einzufügen, nachdem du die EditBoxSeite nocheinmal - geladen hast.
- Vielen Dank für Deine Mühe.", - "ERRORSAVING" => "Beim Abspeichern ist ein Fehler aufgetreten. Bitte versuche es erneut.", - "THANKSFORCONTRIBUTION" => "Vielen Dank für Deinen Beitrag!", - "CANNOTCHANGEPAGE" => "Diese Seite kann nicht geändert werden.", - "OLDVERCOMEBACK" => "Diese alte Version der Seite wieder zur Aktuellen machen", - "PREVIEW" => "Vorschau", - "SAVE" => "Speichern", - "CANCEL_EDIT" => "ÄnderungenVerwerfen", - "UPLOAD_PICTURE_BUTTON" => "Bild hochladen >>>", - "EDIT_FORM_1" => "GuterStil ist es, - ganz einfach das zu schreiben, was einem gerade in den - Sinn kommt. Du solltest dich jetzt noch nicht so sehr - darum kümmern, wie die Seite aussieht. Du kannst später - immernoch zurückkommen und den Text mit WikiTextFormatierungsRegeln - aufputschen.
", - "EDIT_FORM_2" => "
Bitte schreib keine Dinge, die andere Leute - verärgern könnten. Und bedenke auch, daß es schnell auf - dich zurückfallen kann wenn du verschiedene andere Dinge sagst (mehr Informationen zur - 'IP Adresse' - deines Computers findest du bei Google).", - )); - - #-- InterWiki:Links - $ewiki_config["interwiki"] = @array_merge( - @$ewiki_config["interwiki"], - array( - "javascript" => "", # this actually protects from javascript: links - "url" => "", -# "self" => "this", - "this" => EWIKI_SCRIPT, # better was absolute _URL to ewiki wrapper - "jump" => "" - )); - // BEGIN MOODLE CHANGES - disable interwiki liks by default - // can be enabled with $CFG->wiki_allow_interwiki = true . MDL-19460 - global $CFG; - if (!empty($CFG->wiki_allow_interwiki)) { - $ewiki_config["interwiki"] = @array_merge( - $ewiki_config["interwiki"], - array ( - "ErfurtWiki" => "http://erfurtwiki.sourceforge.net/?id=", - "InterWiki" => "InterWikiSearch", - "InterWikiSearch" => "http://sunir.org/apps/meta.pl?", - "Wiki" => "WardsWiki", - "WardsWiki" => "http://www.c2.com/cgi/wiki?", - "WikiFind" => "http://c2.com/cgi/wiki?FindPage&value=", - "WikiPedia" => "http://www.wikipedia.com/wiki.cgi?", - "MeatBall" => "MeatballWiki", - "MeatballWiki" => "http://www.usemod.com/cgi-bin/mb.pl?", - "UseMod" => "http://www.usemod.com/cgi-bin/wiki.pl?", - "PhpWiki" => "http://phpwiki.sourceforge.net/phpwiki/index.php3?", - "LinuxWiki" => "http://linuxwiki.de/", - "OpenWiki" => "http://openwiki.com/?", - "Tavi" => "http://andstuff.org/tavi/", - "TWiki" => "http://twiki.sourceforge.net/cgi-bin/view/", - "MoinMoin" => "http://www.purl.net/wiki/moin/", - "Google" => "http://google.com/search?q=", - "ISBN" => "http://www.amazon.com/exec/obidos/ISBN=", - "icq" => "http://www.icq.com/" - )); - } - // END MOODLE CHANGES - - - - - -#-------------------------------------------------------------------- main --- - -/* this is the main function, which you should preferrably call to - integrate the ewiki into your web site; it chains to most other - parts and plugins (including the edit box); - if you do not supply the requested pages "$id" we will fetch it - from the pre-defined possible URL parameters. -*/ -function ewiki_page($id=false) { - - global $ewiki_links, $ewiki_plugins, $ewiki_ring, $ewiki_t, $ewiki_errmsg; - #-- output var - $o = ""; - - #-- selected page - $action = optional_param('action', EWIKI_DEFAULT_ACTION); - $content = optional_param('content', false); - $version = optional_param('version', false); - - if (!strlen($id)) { - $id = ewiki_id(); - } - $id = format_string($id,true); - #-- page action - if ($delim = strpos($id, EWIKI_ACTION_SEP_CHAR)) { - $action = substr($id, 0, $delim); - $id = substr($id, $delim + 1); - } - elseif (!EWIKI_USE_ACTION_PARAM) { - $action = EWIKI_DEFAULT_ACTION; - } - $GLOBALS["ewiki_id"] = $id; - $GLOBALS["ewiki_title"] = ewiki_split_title($id); - $GLOBALS["ewiki_action"] = $action; - - #-- fetch from db - $dquery = array( - "id" => $id - ); - if (!$content && ($dquery["version"] = $version)) { - $dquery["forced_version"] = $dquery["version"]; - } - $data = @array_merge($dquery, ewiki_database("GET", $dquery)); - - #-- stop here if page is not marked as _TEXT, - # perform authentication then, and let only administrators proceed - if (!empty($data["flags"]) && (($data["flags"] & EWIKI_DB_F_TYPE) != EWIKI_DB_F_TEXT)) { - if (($data["flags"] & EWIKI_DB_F_BINARY) && ($pf = $ewiki_plugins["handler_binary"][0])) { - return($pf($id, $data, $action)); //_BINARY entries handled separately - } - elseif (!EWIKI_PROTECTED_MODE || !ewiki_auth($id, $data, $action, 0, 1) && ($ewiki_ring!=0)) { - return(ewiki_t("DISABLEDPAGE")); - } - } - - #-- pre-check if actions exist - $pf_page = ewiki_array($ewiki_plugins["page"], $id); - - #-- edit
for non-existent pages - if (($action==EWIKI_DEFAULT_ACTION) && empty($data["content"]) && empty($pf_page)) { - if (EWIKI_AUTO_EDIT) { - $action = "edit"; - } - else { - $data["content"] = ewiki_t("DOESNOTEXIST"); - } - } - #-- more initialization - if ($pf_a = @$ewiki_plugins["page_init"]) { - ksort($pf_a); - foreach ($pf_a as $pf) { - $o .= $pf($id, $data, $action); - } - unset($ewiki_plugins["page_init"]); - } - $pf_page = ewiki_array($ewiki_plugins["page"], $id); - - #-- require auth - if (EWIKI_PROTECTED_MODE) { - if (!ewiki_auth($id, $data, $action, $ring=false, $force=EWIKI_AUTO_LOGIN)) { - return($o.=$ewiki_errmsg); - } - } - - #-- handlers - $handler_o = ""; - if ($pf_a = @$ewiki_plugins["handler"]) { - ksort($pf_a); - foreach ($pf_a as $pf) { - if ($handler_o = $pf($id, $data, $action)) { break; } - } } - - #-- finished by handler - if ($handler_o) { - $o .= $handler_o; - } - #-- actions that also work for static and internal pages - elseif (($pf = @$ewiki_plugins["action_always"][$action]) && function_exists($pf)) { - $o .= $pf($id, $data, $action); - } - #-- internal pages - elseif ($pf_page && function_exists($pf_page)) { - $o .= $pf_page($id, $data, $action); - } - #-- page actions - else { - $pf = @$ewiki_plugins["action"][$action]; - - #-- fallback to "view" action - if (empty($pf) || !function_exists($pf)) { - - $pf = "ewiki_page_view"; - $action = "view"; // we could also allow different (this is a - // catch-all) view variants, but this would lead to some problems - } - - $o .= $pf($id, $data, $action); - } - - #-- error instead of page? - if (empty($o) && $ewiki_errmsg) { - $o = $ewiki_errmsg; - } - - #-- html post processing - if ($pf_a = $ewiki_plugins["page_final"]) { - ksort($pf_a); - foreach ($pf_a as $pf) { - if ($action == 'edit' and $pf == 'ewiki_html_tag_balancer') { - continue; // balancer breaks htmlarea buttons - } - $pf($o, $id, $data, $action); - } - } - - (EWIKI_ESCAPE_AT) && ($o = str_replace("@", "@", $o)); - - return($o); -} - - - -#-- HTTP meta headers -function ewiki_http_headers(&$o, $id, &$data, $action) { - global $ewiki_t; - if (EWIKI_HTTP_HEADERS && !headers_sent()) { - if (!empty($data)) { - if ($uu = @$data["id"]) @header('Content-Disposition: inline; filename="' . urlencode($uu) . '.html"'); - if ($uu = @$data["version"]) @header('Content-Version: ' . $uu); - if ($uu = @$data["lastmodified"]) @header('Last-Modified: ' . gmstrftime($ewiki_t["C"]["DATE"], $uu)); - } - if (EWIKI_NO_CACHE) { - header('Expires: ' . gmstrftime($ewiki_t["C"]["DATE"], UNIX_MILLENNIUM)); - header('Pragma: no-cache'); - header('Cache-Control: no-cache, private, must-revalidate'); - # change to "C-C: cache, must-revalidate" ?? - # private only for authenticated users / _PROT_MODE - } - #-- ETag - if ($data["version"] && ($etag=ewiki_etag($data)) || ($etag=md5($o))) { - $weak = "W/" . urlencode($id) . "." . $data["version"]; - header("ETag: \"$etag\""); ###, \"$weak\""); - } - } -} -function ewiki_etag(&$data) { - return( urlencode($data["id"]) . ":" . dechex($data["version"]) . ":ewiki:" . - dechex(crc32($data["content"]) & 0x7FFFBFFF) ); -} - - - -#-- encloses whole page output with a descriptive
-function ewiki_page_css_container(&$o, &$id, &$data, &$action) { - $o = "
| @µöäüÖÄÜߤ^°«»\'\\', - '- -----------------------------------------------') - . "\">\n" - . $o . "\n
\n"; -} - - - -function ewiki_split_title ($id='', $split=EWIKI_SPLIT_TITLE, $entities=1) { - strlen($id) or ($id = $GLOBALS["ewiki_id"]); - if ($split) { - $id = preg_replace("/([".wiki_get_define('EWIKI_CHARS_L')."])([".wiki_get_define('EWIKI_CHARS_U')."]+)/", "$1 $2", $id); - } - return($entities ? s($id) : $id); -} - - - -function ewiki_add_title(&$html, $id, &$data, $action, $go_action="links") { - $html = ewiki_make_title($id, '', 1, $action, $go_action) . $html; -} - - -function ewiki_make_title($id='', $title='', $class=3, $action="view", $go_action="links", $may_split=1) { - - global $ewiki_config, $ewiki_plugins, $ewiki_title, $ewiki_id; - - #-- advanced handler - if ($pf = @$ewiki_plugins["make_title"][0]) { - return($pf($title, $class, $action, $go_action, $may_split)); - } - #-- disabled - elseif (!$ewiki_config["print_title"]) { - return(""); - } - - #-- get id - if (empty($id)) { - $id = $ewiki_id; - } - - #-- get title - if (!strlen($title)) { - $title = $ewiki_title; // already in &html; format - } - elseif ($ewiki_config["split_title"] && $may_split) { - $title = ewiki_split_title($title, $ewiki_config["split_title"], 0&($title!=$ewiki_title)); - } - else { - $title = s($title); - } - - #-- title mangling - if ($pf_a = @$ewiki_plugins["title_transform"]) { - foreach ($pf_a as $pf) { $pf($id, $title, $go_action); } - } - - #-- clickable link or simple headline - if ($class <= $ewiki_config["print_title"]) { - if ($uu = @$ewiki_config["link_title_action"][$action]) { - $go_action = $uu; - } - if ($uu = @$ewiki_config["link_title_url"]) { - $href = $uu; - unset($ewiki_config["link_title_url"]); - } - else { - $href = ewiki_script($go_action, $id); - } - $o = '' . ($title) . ''; - } - else { - $o = $title; - } - - return('

' . $o . '

'."\n"); -} - - - - -function ewiki_page_view($id, &$data, $action, $all=1) { - - global $ewiki_plugins, $ewiki_config; - $o = ""; - - $thanks = optional_param('thankyou', '', PARAM_CLEAN); - - #-- render requested wiki page <-- goal !!! - $render_args = array( - "scan_links" => 1, - "html" => (EWIKI_ALLOW_HTML||(@$data["flags"]&EWIKI_DB_F_HTML)), - ); - $o .= $ewiki_plugins["render"][0] ($data["content"], $render_args); - if (!$all) { - return($o); - } - #### MOODLE CHANGE - /// Add Moodle filters to text porion of wiki. - global $moodle_format; // from wiki/view.php - $o = format_text($o, $moodle_format); - $o.= "

"; - - #-- control line + other per-page info stuff - if ($pf_a = $ewiki_plugins["view_append"]) { - ksort($pf_a); - foreach ($pf_a as $n => $pf) { $o .= $pf($id, $data, $action); } - } - if ($pf_a = $ewiki_plugins["view_final"]) { - ksort($pf_a); - foreach ($pf_a as $n => $pf) { $pf($o, $id, $data, $action); } - } - - if (!empty($thanks) && $ewiki_config["edit_thank_you"]) { - $o = ewiki_t("THANKSFORCONTRIBUTION") . $o; - } - - - if (EWIKI_HIT_COUNTING) { - ewiki_database("HIT", $data); - } - - return($o); -} - - - - -#-------------------------------------------------------------------- util --- - - -/* retrieves "$id/$action" string from URL / QueryString / PathInfo, - change this in conjunction with ewiki_script() to customize your URLs - further whenever desired -*/ -function ewiki_id() { - ($id = optional_param("id", '', PARAM_CLEAN)) or - ($id = optional_param("name", '', PARAM_CLEAN)) or - ($id = optional_param("page", '', PARAM_CLEAN)) or - ($id = optional_param("file", '', PARAM_CLEAN)) or - (EWIKI_USE_PATH_INFO) and ($id = ltrim(@$_SERVER["PATH_INFO"], "/")) or - (!isset($_REQUEST["id"])) and ($id = trim(strtok($_SERVER["QUERY_STRING"], "&"))); - if (!strlen($id) || ($id=="id=")) { - $id = EWIKI_PAGE_INDEX; - } - (EWIKI_URLDECODE) && ($id = urldecode($id)); - return($id); -} - - - - -/* replaces EWIKI_SCRIPT, works more sophisticated, and - bypasses various design flaws - - if only the first parameter is used (old style), it can contain - a complete "action/WikiPage" - but this is ambigutious - - else $asid is the action, and $id contains the WikiPageName - - $ewiki_config["script"] will now be used in favour of the constant - - needs more work on _BINARY, should be a separate function -*/ -## MOODLE-CHANGE: $asid="", Knows the devil why.... -function ewiki_script($asid="", $id=false, $params="", $bin=0, $html=1, $script=NULL) { - global $ewiki_config, $ewiki_plugins; - - #-- get base script url from config vars - if (empty($script)) { - $script = &$ewiki_config[!$bin?"script":"script_binary"]; - } - - - #-- separate $action and $id for old style requests - if ($id === false) { - if (strpos($asid, EWIKI_ACTION_SEP_CHAR) !== false) { - $asid = strtok($asid, EWIKI_ACTION_SEP_CHAR); - $id = strtok("\000"); - } - else { - $id = $asid; - $asid = ""; - } - } - - #-- prepare params - if (is_array($params)) { - $uu = $params; - $params = ""; - if ($uu) foreach ($uu as $k=>$v) { - $params .= (strlen($params)?"&":"") . rawurlencode($k) . "=" . rawurlencode($v); - } - } - #-- action= parameter - if (EWIKI_USE_ACTION_PARAM >= 2) { - $params = "action=$asid" . (strlen($params)?"&":"") . $params; - $asid = ""; - } - - #-- workaround slashes in $id - if (empty($asid) && (strpos($id, EWIKI_ACTION_SEP_CHAR) !== false) && !$bin) { - $asid = "view"; - } - /*paranoia*/ $asid = trim($asid, EWIKI_ACTION_SEP_CHAR); - - #-- make url - if (EWIKI_URLENCODE) { - $id = urlencode($id); - $asid = urlencode($asid); - } - else { - # only urlencode &, %, ? for example - } - $url = $script; - if ($asid) { - $id = $asid . EWIKI_ACTION_SEP_CHAR . $id; #= "action/PageName" - } - if (strpos($url, "%s") !== false) { - $url = str_replace("%s", $id, $url); - } - else { - $url .= $id; - } - - #-- add url params - if (strlen($params)) { - $url .= (strpos($url,"?")!==false ? "&":"?") . $params; - } - #-- fin - if ($html) { - //Don't replace & if it's part of encoded character (bug 2209) - $url = preg_replace("/&(?![A-Za-z]{0,4}\w{2,3};|#[0-9]{2,5};)/","&", $url); - } else { - //This is going to be used in some header or meta redirect, so It cannot use & (bug 2620) - $url = preg_replace('/&/', '&', $url); - } - return($url); -} - - -/* this ewiki_script() wrapper is used to generate URLs to binary - content in the ewiki database -*/ -function ewiki_script_binary($asid, $id=false, $params=array(), $upload=0) { - - $upload |= is_string($params) && strlen($params) || count($params); - - #-- generate URL directly to the plainly saved data file, - # see also plugins/binary_store - - if (defined("EWIKI_DB_STORE_URL") && !$upload) { - $url = EWIKI_DB_STORE_URL . rawurlencode($id); - } - - #-- else get standard URL (thru ewiki.php) from ewiki_script() - else { - $url = ewiki_script($asid, $id, $params, "_BINARY=1"); - } - - return($url); -} - - -/* this function returns the absolute ewiki_script url, if EWIKI_SCRIPT_URL - is set, else it guesses the value -*/ -function ewiki_script_url() { - - global $ewiki_action, $ewiki_id, $ewiki_config; - - $scr_template = $ewiki_config["script"]; - $scr_current = ewiki_script($ewiki_action, $ewiki_id); - $req_uri = $_SERVER["REQUEST_URI"]; - - if ($url = $ewiki_config["script_url"]) { - return($url); - } - elseif (strpos($req_uri, $scr_current) !== false) { - $url = str_replace($req_uri, $scr_current, $scr_template); - } - elseif (strpos($req_uri, "?") && (strpos($scr_template, "?") !== false)) { - $url = substr($req_uri, 0, strpos($req_uri, "?")) - . substr($scr_template, strpos($scr_template, "?")); - } - elseif (strpos($req_uri, $sn = $_SERVER["SCRIPT_NAME"])) { - $url = $sn . "?id="; - } - else { - return(NULL); #-- could not guess it - } - - #$url = "http://" . $_SERVER["SERVER_NAME"] . $url; - return($url); -} - - - - -#------------------------------------------------------------ page plugins --- - - - -function ewiki_page_links($id, &$data, $action) { - $o = ewiki_make_title($id, ewiki_t("PAGESLINKINGTO", array("title"=>$id)), 1, $action, "", "_MAY_SPLIT=1"); - if ($pages = ewiki_get_backlinks($id)) { - $o .= ewiki_list_pages($pages); - } else { - $o .= ewiki_t("This page isn't linked from anywhere else."); - } - return($o); -} - -function ewiki_get_backlinks($id) { - $result = ewiki_database("SEARCH", array("refs" => $id)); - $pages = array(); - while ($row = $result->get(0, 0x0020)) { - if ( strpos($row["refs"], "\n$id\n") !== false) { - $pages[] = $row["id"]; - } - } - return($pages); -} - -function ewiki_get_links($id) { - if ($data = ewiki_database("GET", array("id"=>$id))) { - $refs = explode("\n", trim($data["refs"])); - $r = array(); - foreach (ewiki_database("FIND", $refs) as $id=>$exists) { - if ($exists) { - $r[] = $id; - } - } - return($r); - } -} - - -function ewiki_list_pages($pages=array(), $limit=EWIKI_LIST_LIMIT, - $value_as_title=0, $pf_list=false) -{ - global $ewiki_plugins; - $o = ""; - - $is_num = !empty($pages[0]); - $lines = array(); - $n = 0; - - foreach ($pages as $id=>$add_text) { - - $title = $id; - $params = ""; - - if (is_array($add_text)) { - list($id, $params, $title, $add_text) = $add_text; - } - elseif ($is_num) { - $id = $title = $add_text; - $add_text = ""; - } - elseif ($value_as_title) { - $title = $add_text; - $add_text = ""; - } - - $lines[] = '' . s($title) . ' ' . $add_text; - - if (($limit > 0) && ($n++ >= $limit)) { - break; - } - } - - if ($pf_a = @$ewiki_plugins["list_transform"]) - foreach ($pf_a as $pf_transform) { - $pf_transform($lines); - } - - if (($pf_list) || ($pf_list = @$ewiki_plugins["list_pages"][0])) { - $o = $pf_list($lines); - } - elseif($lines) { - $o = "· " . implode("
\n· ", $lines) . "
\n"; - } - - return($o); -} - - - - -function ewiki_page_ordered_list($orderby="created", $asc=0, $print, $title) { - - $o = ewiki_make_title("", $title, 2, ".list", "links", 0); - - $sorted = array(); - $result = ewiki_database("GETALL", array($orderby)); - - while ($row = $result->get()) { - $row = ewiki_database("GET", array( - "id" => $row["id"], - ($asc >= 0 ? "version" : "uu") => 1 // version 1 is most accurate for {hits} - )); - #-- text page? - if (EWIKI_DB_F_TEXT == ($row["flags"] & EWIKI_DB_F_TYPE)) { - #-- viewing allowed? - if (!EWIKI_PROTECTED_MODE || !EWIKI_PROTECTED_MODE_HIDING || ewiki_auth($row["id"], $row, "view")) { - $sorted[$row["id"]] = $row[$orderby]; - } - } - } - - if ($asc != 0) { arsort($sorted); } - else { asort($sorted); } - - foreach ($sorted as $name => $value) { - if (empty($value)) { $value = "0"; } - ##### BEGIN MOODLE ADDITION ##### - #$sorted[$name] = strftime(str_replace('%n', $value, $print), $value); - if($print=="LASTCHANGED") { - $value=strftime("%c",$value); - } - $sorted[$name] = get_string(strtolower($print),"wiki",$value); - ##### BEGIN MOODLE ADDITION ##### - } - $o .= ewiki_list_pages($sorted); - - return($o); -} - - - -function ewiki_page_newest($id=0, $data=0) { - return( ewiki_page_ordered_list("created", 1, "LASTCHANGED", ewiki_t(EWIKI_PAGE_NEWEST)) ); -} - -function ewiki_page_updates($id=0, $data=0) { - return( ewiki_page_ordered_list("lastmodified", -1, "LASTCHANGED", ewiki_t(EWIKI_PAGE_UPDATES)) ); -} - -function ewiki_page_hits($id=0, $data=0) { - ##### BEGIN MOODLE ADDITION ##### - return( ewiki_page_ordered_list("hits", 1, "hits", ewiki_t(EWIKI_PAGE_HITS)) ); -} - -function ewiki_page_versions($id=0, $data=0) { - return( ewiki_page_ordered_list("version", -1, "changes", ewiki_t(EWIKI_PAGE_VERSIONS)) ); - ##### END MOODLE ADDITION ##### -} - - - - - - - -function ewiki_page_search($id, &$data, $action) { - - global $CFG; - - $q = optional_param('q', '', PARAM_CLEAN); - $o = ewiki_make_title($id, $id, 2, $action); - - if ($q == '') { - - $o .= ''; - $o .= '
'; - $o .= '

'; - $o .= ''; - $o .= '
'; - $o .= ''; - } - else { - $found = array(); - - if ($CFG->unicodedb) { - $q = preg_replace('/\s*[\W]+\s*/u', ' ', $q); - } else { - $q = preg_replace('/\s*[^\w]+\s*/', ' ', $q); - } - foreach (explode(" ", $q) as $search) { - - if (empty($search)) { continue; } - - $result = ewiki_database("SEARCH", array("content" => $search)); - - while ($row = $result->get()) { - - #-- show this entry in page listings? - if (EWIKI_PROTECTED_MODE && EWIKI_PROTECTED_MODE_HIDING && !ewiki_auth($row["id"], $row, "view")) { - continue; - } - - $found[] = $row["id"]; - } - } - - $o .= ewiki_list_pages($found); - } - - return($o); -} - - - - - - - - -function ewiki_page_info($id, &$data, $action) { - - global $ewiki_plugins, $ewiki_config, $ewiki_links; - global $CFG, $COURSE, $DB, $OUTPUT; // MOODLE HACK - - $pnum = optional_param(EWIKI_UP_PAGENUM, 0, PARAM_INT); - $pend = optional_param(EWIKI_UP_PAGEEND, 0, PARAM_INT); - - $o = ewiki_make_title($id, ewiki_t("INFOABOUTPAGE")." '{$id}'", 2, $action,"", "_MAY_SPLIT=1"); - - $flagnames = array( - "TEXT", "BIN", "DISABLED", "HTML", "READONLY", "WRITEABLE", - "APPENDONLY", "SYSTEM", - ); - $show = array( - "version", "author", "userid", "created", - "lastmodified", "refs", - "flags", "meta", "content" - ); - - #-- versions to show - $v_start = $data["version"]; - if ( $pnum && ($pnum<=$v_start) ) { - $v_start = $pnum; - } - $v_end = $v_start - $ewiki_config["list_limit"] + 1; - if ( $pend && ($pend<=$v_start) ) { - $v_end = $pend; - } - $v_end = max($v_end, 1); - - #-- go - # the very ($first) entry is rendered more verbosely than the others - for ($v=$v_start,$first=1; ($v>=$v_end); $v--,$first=0) { - - $current = ewiki_database("GET", array("id"=>$id, "version"=>$v)); - - if (!strlen(trim($current["id"])) || !$current["version"] || !strlen(trim($current["content"]))) { - continue; - } - - $o .= '' . "\n"; - - #-- additional info-actions - $commands = ''; - foreach ($ewiki_config["action_links"]["info"] as $thisaction=>$title) - if (@$ewiki_plugins["action"][$thisaction] || @$ewiki_plugins["action_always"][$thisaction]) { - ##### BEGIN MOODLE ADDITION ##### - if ($commands) { - $commands .= '  '; - } - $commands .= '$current["version"])) . - '">' . get_string($title,"wiki") . ''; - ##### END MOODLE ADDITION ##### - } - - #-- print page database entry - foreach($show as $i) { - - $value = @$current[$i]; - - #-- show database {fields} differently - if ($i == "meta") { - continue; // MOODLE DOESN'T USE IT - $str = ""; - if ($first && $value) { foreach ($value as $n=>$d) { - $str .= s("$n: $d") . "
\n"; - } } - $value = $str; - } - elseif ($value >= UNIX_MILLENNIUM) { #-- {lastmodified}, {created} - #### BEGIN MOODLE CHANGE - $value=userdate($value); - #$value = strftime("%c", $value); - #### END MOODLE CHANGE - } - elseif ($i == "content") { - continue; // MOODLE DOESN'T CARE - $value = strlen(trim($value)) . " bytes"; - $i = "content size"; - } - elseif ($first && ($i == "refs") && !(EWIKI_PROTECTED_MODE && (EWIKI_PROTECTED_MODE_HIDING>=2))) { - $a = explode("\n", trim($value)); - $ewiki_links = ewiki_database("FIND", $a); - ewiki_merge_links($ewiki_links); - foreach ($a as $n=>$link) { - $a[$n] = ewiki_link_regex_callback(array("$link"), "force_noimg"); - } - $value = trim(implode(", ", $a)); - if (!$value) { - continue; - } - } - elseif (strpos($value, "\n") !== false) { #-- also for {refs} - $value = str_replace("\n", ", ", trim($value)); - if (!$value) { - continue; - } - } - elseif ($i == "version") { - $value = '$value)) . '">' . - $value . ' '."($commands)"; - } - elseif ($i == "flags") { - continue; // MOODLE DOESN'T USE IT - $fstr = ""; - for ($n = 0; $n < 32; $n++) { - if ($value & (1 << $n)) { - if (! ($s=$flagnames[$n])) { $s = "UU$n"; } - $fstr .= $s . " "; - } - } - $value = $fstr; - } - elseif ($i == "author") { - continue; - $ewiki_links=1; - $value = preg_replace_callback("/((\w+:)?([".wiki_get_define('EWIKI_CHARS_U')."]+[".wiki_get_define('EWIKI_CHARS_L')."]+){2,}[\w\d]*)/", "ewiki_link_regex_callback", $value); - } - elseif ($i == "userid") { - $i = 'author'; - if ($user = $DB->get_record('user', array('id'=>$value))) { - if (!isset($COURSE->id)) { - $COURSE->id = SITEID; - } - $picture = $OUTPUT->user_picture($user); - $value = $picture . html_writer::link("$CFG->wwwroot/user/view.php?id=$user->id&course=$COURSE->id", fullname($user)); - } else { - continue; - //$value = @$current['author']; - } - } - - ##### BEGIN MOODLE ADDITION ##### - $o .= '' . - '\n"; - ##### END MOODLE ADDITION ##### - - } - - $o .= "
' .ewiki_t($i). ':' . $value . "


\n"; - - } - - #-- page result split - if ($v >= 1) { - $o .= "
\n".get_string('showversions','wiki').' '.ewiki_chunked_page($action, $id, -1, $v, 1, 0, 0) . "\n
"; - } - - return($o); -} - - - - -function ewiki_chunked_page($action, $id, $dir=-1, $start=10, $end=1, $limit=0, $overlap=0.25, $collapse_last=0.67) { - - global $ewiki_config; - - if (empty($limit)) { - $limit = $ewiki_config["list_limit"]; - } - if ($overlap < 1) { - $overlap = (int) ($limit * $overlap); - } - - $p = ""; - $n = $start; - - while ($n) { - - $n -= $dir * $overlap; - - $e = $n + $dir * ($limit + $overlap) + 1; - - if ($dir<0) { - $e = max(1, $e); - if ($e <= $collapse_last * $limit) { - $e = 1; - } - } - else { - $e = min($end, $e); - if ($e >= $collapse_last * $limit) { - $e = $end; - } - } - - $o .= ($o?" · ":"") - . ''. "$n-$e" . ''; - - if (($n=$e-1) < $end) { - $n = false; - } - } - - return(''. $o .''); -} - - - - - - -function ewiki_page_edit($id, $data, $action) { - - global $ewiki_links, $ewiki_author, $ewiki_plugins, $ewiki_ring, $ewiki_errmsg; - - $content = optional_param('content', '', PARAM_CLEAN); - $version = optional_param('version', '', PARAM_CLEAN); - $preview = optional_param('preview', false, PARAM_BOOL); - $save = optional_param('save', false, PARAM_BOOL); - - $hidden_postdata = array(); - - #-- previous version come back - if (@$data["forced_version"]) { - - $current = ewiki_database("GET", array("id"=>$id)); - $data["version"] = $current["version"]; - unset($current); - - /// Is this done for somewhere else? - $_REQUEST['content'] = $_POST['content'] = $_GET['content'] = null; - $_REQUEST['version'] = $_POST['version'] = $_GET['version'] = null; - $content = ''; - $version = ''; - } - - #-- edit hacks - if ($pf_a = @$ewiki_plugins["edit_hook"]) foreach ($pf_a as $pf) { - if ($output = $pf($id, $data, $hidden_postdata)) { - return($output); - } - } - - #-- permission checks - if (isset($ewiki_ring)) { - $ring = $ewiki_ring; - } else { - $ring = 3; - } - $flags = @$data["flags"]; - if (!($flags & EWIKI_DB_F_WRITEABLE)) { - - #-- perform auth - $edit_ring = (EWIKI_PROTECTED_MODE>=2) ? (2) : (NULL); - if (EWIKI_PROTECTED_MODE && !ewiki_auth($id, $data, $action, $edit_ring, "FORCE")) { - return($ewiki_errmsg); - } - - #-- flag checking - if (($flags & EWIKI_DB_F_READONLY) and ($ring >= 2)) { - return(ewiki_t("CANNOTCHANGEPAGE")); - } - if (($flags) and (($flags & EWIKI_DB_F_TYPE) != EWIKI_DB_F_TEXT) and ($ring >= 1)) { - return(ewiki_t("CANNOTCHANGEPAGE")); - } - } - - #-- "Edit Me" - $o = ewiki_make_title($id, ewiki_t("EDITTHISPAGE").(" '{$id}'"), 2, $action, "", "_MAY_SPLIT=1"); - - #-- preview - if ($preview) { - $o .= $ewiki_plugins["edit_preview"][0]($data); - } - - #-- save - if ($save) { - - - #-- normalize to UNIX newlines - $content = str_replace("\015\012", "\012", $content); - $content = str_replace("\015", "\012", $content); - - #-- check for concurrent version saving - $error = 0; - if ((@$data["version"] >= 1) && ($data["version"] != $version) || ($version < 1)) { - - $pf = $ewiki_plugins["edit_patch"][0]; - - if (!$pf || !$pf($id, $data)) { - $error = 1; - $o .= ewiki_t("ERRVERSIONSAVE") . "

"; - } - - } - if (!$error) { - - #-- new pages` flags - if (! ($set_flags = @$data["flags"] & EWIKI_DB_F_COPYMASK)) { - $set_flags = 1; - } - if (EWIKI_ALLOW_HTML) { - $set_flags |= EWIKI_DB_F_HTML; - } - - #-- mk db entry - $save = array( - "id" => $id, - "version" => @$data["version"] + 1, - "flags" => $set_flags, - "content" => $content, - "created" => ($uu=@$data["created"]) ? $uu : time(), - "meta" => ($uu=@$data["meta"]) ? $uu : "", - "hits" => ($uu=@$data["hits"]) ? $uu : "0", - ); - ewiki_data_update($save); - - #-- edit storage hooks - if ($pf_a = @$ewiki_plugins["edit_save"]) { - foreach ($pf_a as $pf) { - $pf($save, $data); - } - } - - #-- save - if (!$save || !ewiki_database("WRITE", $save)) { - - $o .= $ewiki_errmsg ? $ewiki_errmsg : ewiki_t("ERRORSAVING"); - - } - else { - #-- prevent double saving, when ewiki_page() is re-called - $_REQUEST = $_GET = $_POST = array(); - - $o = ewiki_t("THANKSFORCONTRIBUTION") . "

"; - $o .= ewiki_page($id); - - if (EWIKI_EDIT_REDIRECT) { - $url = ewiki_script("", $id, "thankyou=1", 0, 0, EWIKI_HTTP_HEADERS?ewiki_script_url():0); - - if (EWIKI_HTTP_HEADERS && !headers_sent()) { - header("Status: 303 Redirect for GET"); - header("Location: $url"); - #header("URI: $url"); - #header("Refresh: 0; URL=$url"); - } - else { - $o .= ''; - } - } - - } - - } - - //@REWORK - // header("Reload-Location: " . ewiki_script("", $id, "", 0, 0, ewiki_script_url()) ); - - } - else { - #-- Edit
- $o .= ewiki_page_edit_form($id, $data, $hidden_postdata); - - #-- additional forms - if ($pf_a = $ewiki_plugins["edit_form_final"]) foreach ($pf_a as $pf) { - $pf($o, $id, $data, $action); - } - } - - return($o); -} - - -function ewiki_data_update(&$data, $author="") { - global $USER, $ewiki_links; - - #-- add backlinks entry - ewiki_scan_wikiwords($data["content"], $ewiki_links, "_STRIP_EMAIL=1"); - $data["refs"] = "\n\n".implode("\n", array_keys($ewiki_links))."\n\n"; - $data["lastmodified"] = time(); - $data["author"] = ewiki_author($author); - if (isset($USER->id)) { - $data["userid"] = $USER->id; - } -} - - - -#-- edit " - . $GLOBALS["ewiki_t"]["C"]["EDIT_TEXTAREA_RESIZE_JS"]; - - ##### BEGIN MOODLE ADDITION ##### - } - ##### END MOODLE ADDITION ##### - - #-- more elements before the submit button - if ($pf_a = $ewiki_plugins["edit_form_insert"]) foreach ($pf_a as $pf) { - $o .= $pf($id, $data, $action); - } - - ##### BEGIN MOODLE ADDITION (Cancel Editing into Button) ##### - $o .= "\n
\n" - . ''."\n" - . '' . "\n" - . '' . "\n"; -# . '   ' . ewiki_t("CANCEL_EDIT") . ''; - ##### END MOODLE ADDITION ##### - - #-- additional form elements - if ($pf_a = $ewiki_plugins["edit_form_append"]) foreach ($pf_a as $pf) { - $o .= $pf($id, $data, $action); - } - - $o .= "\n
\n"; - // . ewiki_t("EDIT_FORM_2"); // MOODLE DELETION - - return('
'. $o .'
'); -} - - - -#-- pic upload form -function ewiki_page_edit_form_final_imgupload(&$o, &$id, &$data, &$action) { - if (EWIKI_SCRIPT_BINARY && EWIKI_UP_UPLOAD && EWIKI_IMAGE_MAXSIZE) { - $o .= "\n
\n". '
' - . '
' - . '
' - . '' - . '' : " />") - . '' - . '   ' - . '' - . '
'. "\n"; - } -} - - -function ewiki_page_edit_preview(&$data) { -#### BEGIN MOODLE CHANGES - global $moodle_format; - $preview_text=$GLOBALS["ewiki_plugins"]["render"][0](optional_param("content", null, PARAM_CLEAN), 1, EWIKI_ALLOW_HTML || (@$data["flags"]&EWIKI_DB_F_HTML)); - return( '
' - . "
" - . "
" . ewiki_t("PREVIEW") . "


\n" - . format_text($preview_text, $moodle_format) - . "



" - . "
" - ); -#### END MOODLE CHANGES -} - - -function ewiki_control_links($id, &$data, $action) { - - global $ewiki_plugins, $ewiki_ring, $ewiki_config; - $action_links = & $ewiki_config["action_links"][$action]; - - #-- disabled - if (!$ewiki_config["control_line"]) { - return(""); - } - - $o = "\n" - . '\n"; - - return($o); -} - - - - - -# ============================================================= rendering === - - - - - -######## ### ### ######### ### ### ### ####### -######## #### ### ######### ### #### ### ####### -### ##### ### ### ##### ### ### -###### ######### ### #### ### ######### ###### -###### ######### ### #### ### ######### ###### -### ### ##### ### ### ### ### ##### ### -######## ### #### ######### ### ### #### ####### -######## ### ### ######### ### ### ### ####### - - -/* - The _format() function transforms $wiki_source pages into strings, - also calls various markup and helper plugins during the transformation - process. The $params array can activate various features and extensions. - only accepts UNIX newlines! -*/ -function ewiki_format ( $wiki_source, $params = array()) { - global $ewiki_links, $ewiki_plugins, $ewiki_config; - - #-- state vars - $params = @array_merge($ewiki_config["format_params"], $params); - $s = array( - "in" => 0, # current input $iii[] block array index - "para" => "", - "line" => "", - "post" => "", # string to append after current line/paragraph - "line_i" => 0, - "lines" => array(), - "list" => "", # lists - "tbl" => 0, # open table? - "indent" => 0, # indentation - "close" => array(), - ); - #-- aliases - $in = &$s["in"]; - $line = &$s["line"]; - $lines = &$s["lines"]; - $para = &$s["para"]; - $post = &$s["post"]; - $list = &$s["list"]; - - #-- input and output arrays - if ($wiki_source[0] == "<") { # also prepend an empty line - $wiki_source = "\n" . $wiki_source; # for faster strpos() searchs - } - $iii = array( - 0 => array( - 0 => $wiki_source."\n", # body + empty line - 1 => 0x0FFF, # flags (0x1=WikiMarkup, 0x2=WikiLinks, 0x100=BlockPlugins) - 2 => "core", # block plugin name - ) - ); - $ooo = array( - ); - unset($wiki_source); - - #-- plugins - $pf_tbl = @$ewiki_plugins["format_table"][0]; - $pf_line = @$ewiki_plugins["format_line"]; - - #-- wikimarkup (wm) - $htmlentities = $ewiki_config["htmlentities"]; - $wm_indent = &$ewiki_config["wm_indent"]; - $wm_table_defaults = &$ewiki_config["wm_table_defaults"]; - $wm_source = &$ewiki_config["wm_source"]; - $wm_list = &$ewiki_config["wm_list"]; - $wm_list_chars = implode("", array_keys($wm_list)); - $wm_style = &$ewiki_config["wm_style"]; - $wm_start_end = &$ewiki_config["wm_start_end"]; - - #-- eleminate html - $iii[0][0] = strtr($iii[0][0], $htmlentities); - unset($htmlentities["&"]); - - #-- pre-processing plugins (working on wiki source) - if ($pf_source = $ewiki_plugins["format_source"]) { - foreach ($pf_source as $pf) $pf($iii[0][0]); - } - - #-- simple markup - $iii[0][0] = strtr($iii[0][0], $wm_source); - - #-- separate input into blocks ------------------------------------------ - foreach ($ewiki_config["format_block"] as $btype => $binfo) { - - #-- disabled block plugin? - if ($binfo[2] && !$params[$binfo[2]]) { - continue; - } - - #-- traverse $iii[] - $in = -1; - while ((++$in) < count($iii)) { - - #-- search fragment delimeters - if ($iii[$in][1] & 0x0100) - while ( - ($c = & $iii[$in][0]) && - (($l = strpos($c, $binfo[0])) !== false) && - ($r = strpos($c, $binfo[1], $l)) ) - { - $l_len = strlen($binfo[0]); - $r_len = strlen($binfo[1]); - - $repl = array(); - // pre-text - if (($l > 0) && trim($text = substr($c, 0, $l))) { - $repl[] = array($text, 0xFFFF, "core"); - } - // the extracted part - if (trim($text = substr($c, $l+$l_len, $r-$l-$r_len))) { - $repl[] = array($text, $binfo[3], "$btype"); - } - // rest - if (($r+$r_len < strlen($c)) && trim($text = substr($c, $r+$r_len))) { - $repl[] = array($text, 0xFFFF, "core"); - } - array_splice($iii, $in, 1, $repl); - - $in += 1; - } - } - } - - #-- run format_block plugins - $in = -1; - while ((++$in) < count($iii)) { - if (($btype = $iii[$in][2]) && ($pf_a = $ewiki_plugins["format_block"][$btype])) { - $c = &$iii[$in][0]; - foreach ($pf_a as $pf) { - # current buffer $c and pointer $in into $iii[] and state $s - $pf($c, $in, $iii, $s, $btype); - } - } - } - - #-- wiki markup ------------------------------------------------------ - $para = ""; - $in = -1; - while ((++$in) < count($iii)) { - #-- wikimarkup - if ($iii[$in][1] & 0x0001) { - - #-- input $lines buffer, and output buffer $ooo array - $lines = explode("\n", $iii[$in][0]); - $ooo[$in] = array( - 0 => "", - 1 => $iii[$in][1] - ); - $out = &$ooo[$in][0]; - $s["block"] = ($iii[$in][2] != "core"); # disables indentation & paragraphs - - #-- walk through wiki source lines - $line_max = count($lines); - foreach ($lines as $s["line_i"]=>$line) { -//echo "
line={$s[line_i]}:".htmlspecialchars($line).":".htmlspecialchars($line[0])."
"; - - #-- empty lines separate paragraphs - if (!strlen($line)) { - ewiki_format_close_para($ooo, $s); - ewiki_format_close_tags($ooo, $s); - if (!$s["block"]) { - $out .= "\n"; - } - } - #-- horiz bar - if (!strncmp($line, "----", 4)) { - $out .= "
\n"; - continue; - } - #-- html comment - #if (!strncmp($line, "<!--", 7)) { - # $out .= "\n"; - # continue; - #} - - ($c0 = $line[0]) - or ($c0 = "\000"); - - #-- tables - ### MOODLE CHANGE: TRIM - if (($c0 == "|") && ($line[strlen(trim($line))-1] == "|")) { - if (!$s["tbl"]) { - ewiki_format_close_para($ooo, $s); - ewiki_format_close_tags($ooo, $s); - $s["list"] = ""; - } - $line = substr($line, 1, -1); - if ($pf_tbl) { - $pf_tbl($line, $ooo, $s); - } - else { - if (!$s["tbl"]) { - $out .= "\n"; - $s["close"][] = "\n
"; - } - $line = "\n" . str_replace("|", "\n", $line) . "\n"; - } - $s["tbl"] = 1; - $para = false; - } - elseif ($s["tbl"]) { - $s["tbl"] = 0; - } - - - #-- headlines - if (($c0 == "!") && ($excl = strspn($line, "!"))) { - if ($excl > 3) { - $excl = 3; - } - $line = substr($line, $excl); - $excl = 5 - $excl; - $line = "" . $line . ""; - if ($para) { - ewiki_format_close_para($ooo, $s); - } - ewiki_format_close_tags($ooo, $s); - $para = false; - } - - #-- whole-line markup - # ??? - - - #-- indentation (space/tab markup) - $n_indent = 0; - if (!$list && (!$s["block"]) && ($n_indent = strspn($line, " "))) { - $n_indent = (int) ($n_indent / 2.65); - while ($n_indent > $s["indent"]) { - $out .= $wm_indent; - $s["indent"]++; - } - } - while ($n_indent < $s["indent"]) { - $out .= ""; - $s["indent"]--; - } - - - #-- text style triggers - foreach ($wm_style as $find=>$replace) { - $find_len = strlen($find); - $loop = 20; - while(($loop--) && (($l = strpos($line, $find)) !== false) && ($r = strpos($line, $find, $l + $find_len))) { - $line = substr($line, 0, $l) . $replace[0] . - substr($line, $l + strlen($find), $r - $l - $find_len) . - $replace[1] . substr($line, $r + $find_len); - } - } - - - #-- list markup - if (isset($wm_list[$c0])) { - if (!$list) { - ewiki_format_close_para($ooo, $s); - ewiki_format_close_tags($ooo, $s); - } - $new_len = strspn($line, $wm_list_chars); - $new_list = substr($line, 0, $new_len); - $old_len = strlen($list); - $lchar = $new_list[$new_len-1]; - list($lopen, $ltag1, $ltag2) = $wm_list[$lchar]; - - #-- cut line - $line = substr($line, $new_len); - $lspace = ""; - $linsert = ""; - if ($ltag1) { - $linsert = "<$ltag1>" . strtok($line, $lchar) . " "; - $line = strtok("\000"); - } - - #-- add another
  • st entry - if ($new_len == $old_len) { - $lspace = str_repeat(" ", $new_len); - $out .= "\n" . $lspace . $linsert . "<$ltag2>"; - } - #-- add list - elseif ($new_len > $old_len) { - while ($new_len > ($old_len=strlen($list))) { - $lchar = $new_list[$old_len]; - $list .= $lchar; - list($lopen, $ltag1, $ltag2) = $wm_list[$lchar]; - $lclose = strtok($lopen, " "); - $lspace = str_repeat(" ", $new_len); - - $out .= "\n$lspace<$lopen>\n" . "$lspace". $linsert . "<$ltag2>"; - $s["close"][] = "$lspace"; - $s["close"][] = "$lspace"; - } - } - #-- close lists - else { - while ($new_len < ($old_len=strlen($list))) { - $remove = $old_len-$new_len; - ewiki_format_close_tags($ooo, $s, 2*$remove); - $list = substr($list, 0, -$remove); - } - if ($new_len) { - $lspace = str_repeat(" ", $new_len); - $out .= "$lspace\n" . $lspace . $linsert . "<$ltag2>"; - } - } - - $list = $new_list; - $para = false; - } - elseif ($list) { - if ($c0 == " ") { - $para = false; - } - else { - ewiki_format_close_tags($ooo, $s); - $list = ""; - } - } - - - #-- start-end markup - foreach ($wm_start_end as $d) { - $len0 = strlen($d[0]); - $loop = 20; - while(($loop--) && (($l = strpos($line, $d[0])) !== false) && ($r = strpos($line, $d[1], $l + $len0))) { - $len1 = strlen($d[1]); - $line = substr($line, 0, $l) . $d[2] . - substr($line, $l + $len0, $r - $l - $len0) . - $replace[1] . substr($line, $r + $len1); - } - } - - #-- call wiki source formatting plugins that work on current line - if ($pf_line) { - foreach ($pf_line as $pf) $pf($out, $line, $post); - } - - - - #-- add formatted line to page-output - $line .= $post; - if ($para === false) { - $out .= $line; - $para = ""; - } - else { - $para .= $line . "\n"; - } - - } - - #-- last block, or next not WikiSource? - if (!isset($iii[$in+1]) || !($iii[$in+1][1] & 0x0011)) { - ewiki_format_close_para($ooo, $s); - ewiki_format_close_tags($ooo, $s); - } - } - #-- copy as is into output buffer - else { - $ooo[$in] = $iii[$in]; - } - $iii[$in] = array(); - } - - #-- wiki linking ------------------------------------------------------ - $scan_src = ""; - for ($in=0; $in $ooo[$in][0] . "\n" . $ooo[$in+1][0], - 1 => $ooo[$in][1] | $ooo[$in+1][1], - ); - array_splice($ooo, $in+1, 1); - } - } - $scan_src .= $ooo[$in][0]; - } - - - #-- pre-scan - if (1+$params["scan_links"]) { - ewiki_scan_wikiwords($scan_src, $ewiki_links); - } - if ($pf_linkprep = $ewiki_plugins["format_prepare_linking"]) { - foreach ($pf_linkprep as $pf) $pf($scan_src); - } - $scan_src = NULL; - - #-- finally the link-detection-regex - for ($in=0; $in\n"; - } - #### MOODLE CHANGES - } - #-- paragraph formation plugins - if ($pf_a = $GLOBALS["ewiki_plugins"]["format_para"]) { - foreach ($pf_a as $pf) { - $pf($s["para"], $ooo, $s); - } - } - $out .= $s["para"]; - $s["para"] = ""; - } - #-- indentation - while ($s["indent"]) { - $out .= ""; - $s["indent"]--; - } -} - - -function ewiki_format_close_tags(&$ooo, &$s, $count=100) { - $out = &$ooo[$s["in"]][0]; - if (!is_array($s) || !is_array($s["close"])) { - die("\$s is garbaged == $s!!"); - } - while (($count--) && ($add = array_pop($s["close"]))) { - $out .= $add . "\n"; - } -} - - -function ewiki_format_pre(&$str, &$in, &$iii, &$s, $btype) { - $str = "
    " . $str . "
    "; -} - - -function ewiki_format_html(&$str, &$in, &$iii, &$s) { - $he = array_reverse($GLOBALS["ewiki_config"]["htmlentities"]); - $str = strtr($str, array_flip($he)); - $str = "" . $str . "\n\n"; -} - - -function ewiki_format_comment(&$str, &$in, &$iii, &$s, $btype) { - $str = ""; -} - - - - -/* unclean pre-scanning for WikiWords in a page, - pre-query to the db */ -function ewiki_scan_wikiwords(&$wiki_source, &$ewiki_links, $se=0) { - - global $ewiki_config; - - #-- find matches - preg_match_all($ewiki_config["wiki_pre_scan_regex"], $wiki_source, $uu); - $uu = @array_merge($uu[1], $uu[2], $uu[3], $uu[4], (array)@$uu[5]); - - #-- clean up list, trim() spaces (allows more unclean regex) - page id unification - foreach ($uu as $i=>$id) { - $uu[$i] = trim($id); - } - unset($uu[""]); - $uu = array_unique($uu); - - #-- query db - $ewiki_links = ewiki_database("FIND", $uu); - - #-- strip email adresses - if ($se) { - foreach ($ewiki_links as $c=>$uu) { - if (strpos($c, "@") && (strpos($c, ".") || strpos($c, ":"))) { - unset($ewiki_links[$c]); - } - } - } - -} - - - -/* regex on page content, - handled by callback (see below) -*/ -function ewiki_render_wiki_links(&$o) { - - global $ewiki_links, $ewiki_config, $ewiki_plugins; - - #-- merge with dynamic pages list - ewiki_merge_links($ewiki_links); - - #-- replace WikiWords - $link_regex = &$ewiki_config["wiki_link_regex"]; - $o = preg_replace_callback($link_regex, "ewiki_link_regex_callback", $o); - - #-- cleanup - unset($ewiki_links); -} - - -/* - combines with page plugin list, - and makes all case-insensitive -*/ -function ewiki_merge_links(&$ewiki_links) { - global $ewiki_plugins; -#### BEGIN MOODLE CHANGES - global $ewiki_link_case; - $ewiki_link_case=array(); -#### END MOODLE CHANGES - if ($ewiki_links !== true) { - foreach ($ewiki_plugins["page"] as $page=>$uu) { - $ewiki_links[$page] = 1; - } -#### BEGIN MOODLE CHANGES - foreach($ewiki_links as $page => $uu) { - if($uu) { - $ewiki_link_case[strtolower($page)]=$page; - } - } -#### END MOODLE CHANGES - $ewiki_links = ewiki_array($ewiki_links); - } -} - - - - -/* link rendering (p)regex callback - (ooutch, this is a complicated one) -*/ -function ewiki_link_regex_callback($uu, $force_noimg=0) { - global $DB, $CFG; - #print "
    "; print_r($uu); print "
    "; - global $ewiki_links, $ewiki_plugins, $ewiki_config, $ewiki_id; - - $str = trim($uu[0]); - $type = array(); - $states = array(); - - #-- link bracket '[' escaped with '!' or '~' - if (($str[0] == "!") || ($str[0] == "~")) { - return(substr($str, 1)); - } - if ($str[0] == "#") { - $states["define"] = 1; - $str = substr($str, 1); - } - if ($str[0] == "[") { - $states["brackets"] = 1; - $str = substr($str, 1, -1); - } - - #-- explicit title given via [ title | WikiLink ] - $href = $title = strtok($str, "|"); - if ($uu = strtok("|")) { - $parts = explode('|', $str); - $title = $parts[1] . ' | ' .$parts[0]; - $states["titled"] = 1; - } - #-- title and href swapped: swap back - if (strpos("://", $title) || strpos($title, ":") && !strpos($href, ":")) { - $uu = $title; $title = $href; $href = $uu; - } - - #-- new entitling scheme [ url "title" ] - if ((($l=strpos($str, '"')) < ($r=strrpos($str, '"'))) && ($l!==false) ) { - $title = substr($str, $l + 1, $r - $l - 1); - $href = substr($str, 0, $l) . substr($str, $r + 1); - $states["titled"] = 1; - } - - #-- strip spaces - $spaces_l = ($href[0]==" ") ?1:0; - $spaces_r = ($href[strlen($href)-1]==" ") ?1:0; - $title = ltrim(trim($title), "^"); - $href = ltrim(trim($href), "^"); - - #-- strip_htmlentities() - if (1&& (strpos($href, "&")!==false) && strpos($href, ";")) { - foreach (array("<"=>"<", ">"=>">", "&"=>"&") as $f=>$t) { - $href = str_replace($f, $t, $href); - } - } - - #-- anchors - $href2 = ""; - if (($p = strrpos($href, "#")) && ($p) && ($href[$p-1] != "&")) { - $href2 = trim(substr($href, $p)); - $href = trim(substr($href, 0, $p)); - } - elseif ($p === 0) { - $states["define"] = 1; - } - if ($href == ".") { - $href = $ewiki_id; - } - - #-- for case-insensitivines - $href_i = EWIKI_CASE_INSENSITIVE ? strtolower($href) : ($href); - - #-- injected URLs - if (strpos($inj_url = $ewiki_links[$href_i], "://")) { - if ($href==$title) { $href = $inj_url; } - } - - #-- interwiki links - if (strpos($href, ":") && ($uu = ewiki_interwiki($href, $type))) { - $href = $uu; - $str = "$title"; - } - #-- action:WikiLinks - elseif ($ewiki_plugins["action"][$a=strtolower(strtok($href, ":"))]) { - $type = array($a, "action", "wikipage"); - $str = '' . $title . ''; - } - #-- page anchor definitions, if ($href[0]=="#") - elseif (@$states["define"]) { - $type = array("anchor"); - if ($title==$href) { $title=" "; } - $str = '' . ltrim($title, "#") . ''; - } - #-- inner page anchor jumps - elseif (strlen($href2) && ($href==$ewiki_id) || ($href[0]=="#") && ($href2=&$href)) { - $type = array("jump"); - $str = '' . $title . ''; - } - #-- ordinary internal WikiLinks - elseif (($ewiki_links === true) || @$ewiki_links[$href_i]) { - $type = array("wikipage"); -#### BEGIN MOODLE CHANGES - global $ewiki_link_case; - $href_realcase=array_key_exists($href_i,$ewiki_link_case) ? $ewiki_link_case[$href_i] : $href; - $str = '[[' . $title . ']]'; -#### END MOODLE CHANGES - } - #-- guess for mail@addresses, convert to URI if - elseif (strpos($href, "@") && !strpos($href, ":")) { - $type = array("email"); - $href = "mailto:" . $href; - } - #-- not found fallback - else { - $str = ""; - #-- a plugin may take care - if ($pf_a = $ewiki_plugins["link_notfound"]) { - foreach ($pf_a as $pf) { - if ($str = $pf($title, $href, $href2, $type)) { - break; - } } - } - - #-- (QuestionMarkLink to edit/ action) - if (!$str) { - $type = array("notfound"); - //$str = '' . $title . '?'; - $str = '[['. $title . ']]'; - } - } - - #-- convert standard URLs - foreach ($ewiki_config["idf"]["url"] as $find) - if (strpos($href, $find)===0) { - $type[-2] = "url"; - $type[-1] = strtok($find, ":"); - - #-- URL plugins - if ($pf_a = $ewiki_plugins["link_url"]) foreach ($pf_a as $pf) { - if ($str = $pf($href, $title)) { break 2; } - } - $meta = @$ewiki_links[$href]; - - #-- check for image files - $ext = substr($href, strrpos($href,".")); - $nocache = strpos($ext, "no"); - $ext = strtok($ext, "?&#"); - $obj = in_array($ext, $ewiki_config["idf"]["obj"]); - $img = $obj || in_array($ext, $ewiki_config["idf"]["img"]); - - #-- internal:// references (binary files) - if (EWIKI_SCRIPT_BINARY && ((strpos($href, EWIKI_IDF_INTERNAL)===0) || - EWIKI_IMAGE_MAXSIZE && EWIKI_CACHE_IMAGES && $img && !$nocache) ) - { - $type = array("binary"); - //$href = ewiki_script_binary("", $href); - //##### BEGIN MOODLE ADDITION ##### - $pattern = 'internal://'; - $matches = array(); - $filename = str_replace($pattern, '', $href); - $filename = clean_param($filename, PARAM_FILE); - $href = "@@PLUGINFILE@@/$filename"; - //##### END MOODLE ADDITION ##### - } - - #-- output html reference - if (!$img || $force_noimg || !$states["brackets"] || (strpos($href, EWIKI_IDF_INTERNAL) === 0)) { - $str = '' . $title . ''; - } - #-- img tag - else { - if (is_string($meta)) { - $meta = unserialize($meta); - } - $type = array("image"); - #-- uploaded images size - $x = $meta["width"]; - $y = $meta["height"]; - if ($p = strpos('?', $href)) { #-- width/height given in url - parse_str(str_replace("&", "&", substr($href, $p)), $meta); - ($uu = $meta["x"] . $meta["width"]) and ($x = $uu); - ($uu = $meta["y"] . $meta["height"]) and ($y = $uu); - if ($scale = $meta["r"] . $meta["scale"]) { - ($p = strpos($scale, "%")) and ($scale = strpos($scale, 0, $p) / 100); - $x *= $scale; $y *= $scale; - } - } - $align = array('', ' align="right"', ' align="left"', ' align="center"'); - $align = $align[$spaces_l + 2*$spaces_r]; - $str = ($obj ? '" . ($obj ? "" : ""); - # htmlentities($title) - } - - break; - } - - #-- icon/transform plugins - ksort($type); - if ($pf_a = @$ewiki_plugins["link_final"]) { - foreach ($pf_a as $pf) { $pf($str, $type, $href, $title); } - } - - return($str); -} - - -/* - Returns URL if it encounters an InterWiki:Link or workalike. -*/ -function ewiki_interwiki($href, &$type) { - global $ewiki_config, $ewiki_plugins; - - if (strpos($href, ":") and !strpos($href, "//") and ($p1 = strtok($href, ":"))) { - - $page = strtok("\000"); - - if (!empty($ewiki_config["interwiki"]) && (($p1 = ewiki_array($ewiki_config["interwiki"], $p1)) !== NULL)) { - $type = array("interwiki", $uu); - while ($p1_alias = $ewiki_config["interwiki"][$p1]) { - $type[] = $p1; - $p1 = $p1_alias; - } - if (!strpos($p1, "%s")) { - $p1 .= "%s"; - } - $href = str_replace("%s", $page, $p1); - return($href); - } - elseif ($pf = $ewiki_plugins["intermap"][$p1]) { - return($pf($p1, $page)); - } - } -} - - -/* - implements FeatureWiki:InterMapWalking -*/ -function ewiki_intermap_walking($id, &$data, $action) { - if (empty($data["version"]) && ($href = ewiki_interwiki($id, $uu))) { - header("Location: $href"); - return("$href"); - } -} - - - -# ========================================================================= - - - -##### ## ## ## ## ##### ## ## -###### ## ### ## #### ###### ## ## -## ## ## ### ## ###### ## ## ## ## -##### ## #### ## ## ## ###### ###### -##### ## ####### ###### #### #### -## ### ## ## #### ###### ##### ## -## ### ## ## ### ## ## ## ### ## -###### ## ## ### ## ## ## ## ## -###### ## ## ## ## ## ## ## ## - - - - -/* fetch & store -*/ -function ewiki_binary($break=0) { - global $ewiki_plugins; - global $USER; // MOODLE - - $id = optional_param(EWIKI_UP_BINARY, '', PARAM_CLEAN); - - #-- reject calls - if (!strlen($id) || !EWIKI_IDF_INTERNAL) { - return(false); - } - if (headers_sent()) die("ewiki-binary configuration error"); - - #-- upload requests - $upload_file = @$_FILES[EWIKI_UP_UPLOAD]; - $add_meta = array(); - if ($orig_name = @$upload_file["name"]) { - $add_meta["Content-Location"] = urlencode($orig_name); - $add_meta["Content-Disposition"] = 'inline; filename="'.urlencode(basename("remote://$orig_name")).'"'; - } - - #-- what are we doing here? - if (($id == EWIKI_IDF_INTERNAL) && ($upload_file)) { - $do = "upload"; - } - else { - $data = ewiki_database("GET", array("id" => $id)); - $flags = @$data["flags"]; - if (EWIKI_DB_F_BINARY == ($flags & EWIKI_DB_F_TYPE)) { - $do = "get"; - } - elseif (empty($data["version"]) and EWIKI_CACHE_IMAGES) { - $do = "cache"; - } - else { - $do = "nop"; - } - } - - #-- auth only happens when enforced with _PROTECTED_MODE_XXL setting - # (authentication for inline images in violation of the WWW spirit) - if ((EWIKI_PROTECTED_MODE>=5) && !ewiki_auth($id, $data, "binary-{$do}")) { - $_REQUEST['id'] = $_POST['id'] = $_GET['id'] = "view/BinaryPermissionError"; - return("view/BinaryPermissionError"); - } - - #-- upload an image - if ($do == "upload"){ - $id = ewiki_binary_save_image($upload_file["tmp_name"], "", $return=0, $add_meta); - @unlink($upload_file["tmp_name"]); - ($title = trim($orig_name, "/")) && ($title = preg_replace("/[^-._\w\d]+/", "_", substr(substr($orig_name, strrpos($title, "/")), 0, 20))) - && ($title = '"'.$title.'"') || ($title=""); - - if ($id) { - echo<<File/Picture UploadYour uploaded file was saved as
    -[$id] -.

    -EOF; - } - } - - #-- request for contents from the db - elseif ($do == "get") { -#### CHANGED FOR MOODLE - if (EWIKI_HIT_COUNTING) { - $tmp["id"]=$id; - ewiki_database("HIT", $tmp); - } -#### CHANGED FOR MOODLE - - #-- send http_headers from meta - if (is_array($data["meta"])) { - foreach ($data["meta"] as $hdr=>$val) { - if (($hdr[0] >= "A") && ($hdr[0] <= "Z")) { - header("$hdr: $val"); - } - } - } - - #-- fetch from binary store - if ($pf_a = $ewiki_plugins["binary_get"]) { -#### CHANGED FOR MOODLE - foreach ($pf_a as $pf) { $pf($id, $data["meta"]); } - -#### END CHANGED FOR MOODLE - } - - #-- else fpassthru - echo $data["content"]; - } - - #-- fetch & cache requested URL, - elseif ($do == "cache") { - - #-- check for standard protocol names, to prevent us from serving - # evil requests for '/etc/passwd.jpeg' or '../.htaccess.gif' - if (preg_match('@^\w?(http|ftp|https|ftps|sftp)\w?://@', $id)) { - - #-- generate local copy - $filename = tempnam(EWIKI_TMP, "ewiki.local.temp."); - if (($i = fopen($id, "rb")) && ($o = fopen($filename, "wb"))) { - - while (!feof($i)) { - fwrite($o, fread($i, 65536)); - } - - fclose($i); - fclose($o); - - $add_meta = array( - "Content-Location" => urlencode($id), - "Content-Disposition" => 'inline; filename="'.urlencode(basename($id)).'"' - ); - - $result = ewiki_binary_save_image($filename, $id, "RETURN", $add_meta); - } - } - - #-- deliver - if ($result && !$break) { - ewiki_binary($break=1); - } - #-- mark URL as unavailable - else { - $data = array( - "id" => $id, - "version" => 1, - "flags" => EWIKI_DB_F_DISABLED, - "lastmodified" => time(), - "created" => time(), - "author" => ewiki_author("ewiki_binary_cache"), - "userid" => $USER->id, - "content" => "", - "meta" => array("Status"=>"404 Absent"), - ); - ewiki_database("WRITE", $data); - header("Location: $id"); - ewiki_log("imgcache: did not find '$id', and marked it now in database as DISABLED", 2); - } - - } - - #-- "we don't sell this!" - else { - if (strpos($id, EWIKI_IDF_INTERNAL) === false) { - header("Status: 301 Located SomeWhere Else"); - header("Location: $id"); - } - else { - header("Status: 404 Absent"); - header("X-Broken-URI: $id"); - } - } - - // you should not remove this one, it is really a good idea to use it! - die(); -} - - - - - - -function ewiki_binary_save_image($filename, $id="", $return=0, -$add_meta=array(), $accept_all=EWIKI_ACCEPT_BINARY, $care_for_images=1) -{ - global $ewiki_plugins; - global $USER; // MOODLE - - #-- break on empty files - if (!filesize($filename)) { - return(false); - } - - #-- check for image type and size - $mime_types = array( - "application/octet-stream", - "image/gif", - "image/jpeg", - "image/png", - "application/x-shockwave-flash" - ); - $ext_types = array( - "bin", "gif", "jpeg", "png", "swf" - ); - list($width, $height, $mime_i, $uu) = getimagesize($filename); - (!$mime_i) && ($mime_i=0) || ($mime = $mime_types[$mime_i]); - - #-- images expected - if ($care_for_images) { - - #-- mime type - if (!$mime_i && !$accept_all || !filesize($filename)) { - ewiki_die(ewiki_t("BIN_NOIMG"), $return); - return; - } - - #-- resize image - if (strpos($mime,"image/")!==false) { - if ($pf_a = $ewiki_plugins["image_resize"]) { - foreach ($pf_a as $pf) { - if (EWIKI_IMAGE_RESIZE && (filesize($filename) > EWIKI_IMAGE_MAXSIZE)) { - $pf($filename, $mime, $return); - clearstatcache(); - }}}} - - #-- reject image if too large - if (strlen($content) > EWIKI_IMAGE_MAXSIZE) { - ewiki_die(ewiki_t("BIN_IMGTOOLARGE"), $return); - return; - } - - #-- again check mime type and image sizes - list($width, $height, $mime_i, $uu) = getimagesize($filename); - (!$mime_i) && ($mime_i=0) || ($mime = $mime_types[$mime_i]); - - } - ($ext = $ext_types[$mime_i]) or ($ext = $ext_types[0]); - - #-- binary files - if ((!$mime_i) && ($pf = $ewiki_plugins["mime_magic"][0])) { - if ($tmp = $pf($content)) { - $mime = $tmp; - } - } - if (!strlen($mime)) { - $mime = $mime_types[0]; - } - - #-- store size of binary file - $add_meta["size"] = filesize($filename); - $content = ""; - - #-- handler for (large/) binary content? - if ($pf_a = $ewiki_plugins["binary_store"]) { - foreach ($pf_a as $pf) { - $pf($filename, $id, $add_meta, $ext); - } - } - - #-- read file into memory (2MB), to store it into the database - if ($filename) { - $f = fopen($filename, "rb"); - $content = fread($f, 1<<21); - fclose($f); - } - - #-- generate db file name - if (empty($id)) { - $md5sum = md5($content); - $id = EWIKI_IDF_INTERNAL . $md5sum . ".$ext"; - ewiki_log("generated md5sum '$md5sum' from file content"); - } - - #-- prepare meta data - $meta = @array_merge(array( - "class" => $mime_i ? "image" : "file", - "Content-Type" => $mime, - "Pragma" => "cache", - ), $add_meta); - if ($mime_i) { - $meta["width"] = $width; - $meta["height"] = $height; - } - - #-- database entry - $data = array( - "id" => $id, - "version" => "1", - "author" => ewiki_author(), - "userid" => $USER->id, - "flags" => EWIKI_DB_F_BINARY | EWIKI_DB_F_READONLY, - "created" => time(), - "lastmodified" => time(), - "meta" => &$meta, - "content" => &$content, - ); - - #-- write if not exist - $exists = ewiki_database("FIND", array($id)); - if (! $exists[$id] ) { - $result = ewiki_database("WRITE", $data); - ewiki_log("saving of '$id': " . ($result ? "ok" : "error")); - } - else { - ewiki_log("binary_save_image: '$id' was already in the database", 2); - } - - return($id); -} - - - - -# ========================================================================= - - -#### #### #### ######## ######## -##### ##### #### ########## ########## -###### ###### #### #### ### #### ### -############# #### #### -############# #### ######## #### -#### ### #### #### ######## #### -#### # #### #### #### #### -#### #### #### ### #### #### ### -#### #### #### ######### ########## -#### #### #### ####### ######## - - - -/* yes! it is not neccessary to annoy users with country flags, if the - http already provides means to determine preferred languages! -*/ -function ewiki_localization() { - - global $ewiki_t, $ewiki_plugins; - - $deflangs = ','.@$_ENV["LANGUAGE"] . ','.@$_ENV["LANG"] - . ",".wiki_get_define('EWIKI_DEFAULT_LANG') . ",en,C"; - - foreach (explode(",", @$_SERVER["HTTP_ACCEPT_LANGUAGE"].$deflangs) as $l) { - - $l = strtok($l, ";"); - $l = strtok($l, "-"); $l = strtok($l, "_"); $l = strtok($l, "."); - $l = trim($l); - - $ewiki_t["languages"][] = strtolower($l); - } -} - - - - -/* poor mans gettext, $repl is an array of string replacements to get - applied to the fetched text chunk, - "$const" is either an entry from $ewiki_t[] or a larger text block - containing _{text} replacement braces of the form "_{...}" -*/ -function ewiki_t($const, $repl=array(), $pref_langs=array()) { - ##### BEGIN MOODLE ADDITION ##### - $replacechars=array("." => "", - "," => "", - "!" => "", - ";" => "", - ":" => "", - "'" => "", - '"' => "", - "-" => "", - "_" => "", - " " => "", - "+" => ""); - - $translation=get_string(strtolower(strtr($const,$replacechars)),"wiki",$repl); - return $translation; - ##### END MOODLE ADDITION ##### - -/* global $ewiki_t; - - #-- use default language wishes - if (empty($pref_langs)) { - $pref_langs = $ewiki_t["languages"]; - } - - #-- large text snippet replaceing - if (strpos($const, "_{") !== false) { - while ( (($l=strpos($const,"_{")) || ($l===0)) && ($r=strpos($const,"}",$l)) ) { - $const = substr($const, 0, $l) - . ewiki_t(substr($const, $l+2, $r-$l-2)) - . substr($const,$r+1); - } - } - - #-- just one string - else foreach ($pref_langs as $l) { - - if (is_string($r = @$ewiki_t[$l][$const]) || ($r = @$ewiki_t[$l][strtoupper($const)])) { - - foreach ($repl as $key=>$value) { - if ($key[0] != '$') { - $key = '$'.$key; - } - $r = str_replace($key, $value, $r); - } - return($r); - - } - } - - return($const);*/ -} - - - - - - -function ewiki_log($msg, $error_type=3) { - - if ((EWIKI_LOGLEVEL >= 0) && ($error_type <= EWIKI_LOGLEVEL)) { - - $msg = time() . " - " . - getremoteaddr() . ":" . $_SERVER["REMOTE_PORT"] . " - " . - $_SERVER["REQUEST_METHOD"] . " " . $_SERVER["REQUEST_URI"] . " - " . - strtr($msg, "\n\r\000\377\t\f", "\r\r\r\r\t\f") . "\n"; - error_log($msg, 3, EWIKI_LOGFILE); - } -} - - - - -function ewiki_die($msg, $return=0) { - ewiki_log($msg, 1); - if ($return) { - return($GLOBALS["ewiki_error"] = $msg); - } - else { - die($msg); - } -} - - - -function ewiki_array_hash(&$a) { - return(count($a) . ":" . implode(":", array_keys(array_slice($a, 0, 3)))); -} - - - -/* provides an case-insensitive in_array replacement to search a page name - in a list of others; - the supplied $array WILL be lowercased afterwards, unless $dn was set -*/ -function ewiki_in_array($value, &$array, $dn=0, $ci=EWIKI_CASE_INSENSITIVE) { - - static $as = array(); - - #-- work around pass-by-reference - if ($dn && $ci) { $dest = array(); } - else { $dest = &$array; } - - #-- make everything lowercase - if ($ci) { - $value = strtolower($value); - if (empty($as[ewiki_array_hash($array)])) { // prevent working on the - foreach ($array as $i=>$v) { // same array multiple times - $dest[$i] = strtolower($v); - } - $as[ewiki_array_hash($dest)] = 1; - } - } - - #-- search in values - return(in_array($value, $dest)); -} - - - -/* case-insensitively retrieves an entry from an $array, - or returns the given $array lowercased if $key was obmitted -*/ -function ewiki_array($array, $key=false, $am=1, $ci=EWIKI_CASE_INSENSITIVE) { - - #-- make everything lowercase - if ($ci) { - $key = strtolower($key); - - $r = array(); - foreach ($array as $i=>$v) { - $i = strtolower($i); - if (!$am || empty($r[$i])) { - $r[$i] = $v; - } - else { - $r[$i] .= $v; //RET: doubling for images`meta won't happen - } // but should be "+" here for integers - } - $array = &$r; - } - - #-- search in values - if ($key) { - return(@$array[$key]); - } - else { - return($array); - } -} - - - - - - -function ewiki_author($defstr="") { - - $author = @$GLOBALS["ewiki_author"]; - ($ip = getremoteaddr()) or ($ip = "127.0.0.0"); - ($port = $_SERVER["REMOTE_PORT"]) or ($port = "null"); - $hostname = $ip; - $remote = (($ip != $hostname) ? $hostname . " " : "") - . $ip . ":" . $port; - - (empty($author)) && ( - ($author = $defstr) || - ($author = $_SERVER["HTTP_FROM"]) || // RFC2068 sect 14.22 - ($author = $_SERVER["PHP_AUTH_USER"]) - ); - - (empty($author)) - && ($author = $remote) - || ($author = $author . " (" . $remote . ")" ); - - return($author); -} - - - - - -/* Returns a value of (true) if the currently logged in user (this must - be handled by one of the plugin backends) is authenticated to do the - current $action, or to view the current $id page. - - alternatively just checks current authentication $ring permission level - - errors are returned via the global $ewiki_errmsg -*/ -function ewiki_auth($id, &$data, $action, $ring=false, $request_auth=0) { - - global $ewiki_plugins, $ewiki_ring, $ewiki_author, $ewiki_errmsg; - $ok = true; - $ewiki_errmsg=""; - -#echo "_a($id,dat,$action,$ring,$request_auth)
    \n"; - - if (EWIKI_PROTECTED_MODE) { - - #-- set required vars - if (!isset($ewiki_ring)) { - $ewiki_ring = (int)EWIKI_AUTH_DEFAULT_RING; - } - if ($ring===false) { - $ring = NULL; - } - - #-- plugins to call - $pf_login = @$ewiki_plugins["auth_query"][0]; - $pf_perm = $ewiki_plugins["auth_perm"][0]; - - #-- nobody is currently logged in, so try to fetch username, - # the login
    is not yet enforced - if ($pf_login && empty($ewiki_auth_user)) { - $pf_login($data, 0); - } - - #-- check permission for current request (page/action/ring) - if ($pf_perm) { - - #-- via _auth handler - $ok = $pf_perm($id, $data, $action, $ring, $request_auth); - - #-- if it failed, we really depend on the login , - # and then recall the _perm plugin - if ($pf_login && (($request_auth >= 2) || !$ok && $request_auth && (empty($ewiki_auth_user) || EWIKI_AUTO_LOGIN) && empty($ewiki_errmsg))) { -//@FIXME: complicated if() - strip empty(errmsg) ?? - $pf_login($data, $request_auth); - $ok = $pf_perm($id, $data, $action, $ring, $request_auth=0); - } - } - else { - $ok = !isset($ring) || isset($ring) && ($ewiki_ring <= $ring); - } - - #-- return error string - if (!$ok && empty($ewiki_errmsg)) { - $ewiki_errmsg = ewiki_t("FORBIDDEN"); - } - } - - return($ok); -} - - -/* - Queries all registered ["auth_userdb"] plugins for the given - username, and compares password to against "db" value, sets - $ewiki_ring and returns(true) if valid. -*/ -function ewiki_auth_user($username, $password) { - global $ewiki_ring, $ewiki_errmsg, $ewiki_auth_user, $ewiki_plugins, $ewiki_author; - - if (empty($username)) { - return(false); - } - if (($password[0] == "$") || (strlen($password) > 12)) { - ewiki_log("_auth_userdb: password was transmitted in encoded form, or is just too long (login attemp for user '$username')", 2); - return(false); - } - - if ($pf_u = $ewiki_plugins["auth_userdb"]) - foreach ($pf_u as $pf) { - - if (function_exists($pf) && ($entry = $pf($username, $password))) { - - #-- get and compare password - if ($entry = (array) $entry) { - $enc_pw = $entry[0]; - } - $success = false - || ($enc_pw == substr($password, 0, 12)) - || ($enc_pw == md5($password)) - || ($enc_pw == crypt($password, substr($enc_pw, 0, 2))) - || function_exists("sha1") && ($enc_pw == sha1($password)); - $success &= $enc_pw != "*"; - - #-- return if it matches - if ($success) { - if (isset($entry[1])) { - $ewiki_ring = (int)($entry[1]); - } else { - $ewiki_ring = 2; //(EWIKI_AUTH_DEFAULT_RING - 1); - } - if (empty($ewiki_author)) { - ($ewiki_author = $entry[2]) or - ($ewiki_author = $username); - } - return($success && ($ewiki_auth_user=$username)); - } - } - } - - if ($username || $password) { - ewiki_log("_auth_userdb: wrong password supplied for user '$username', not verified against any userdb", 3); - $ewiki_errmsg = "wrong username and/or password"; -# ewiki_auth($uu, $uu, $uu, $uu, 2); - } - return(false); -} - - - - - -/* reads all files from "./init-pages/" into the database, - when ewiki is run for the very first time and the FrontPage - does not yet exist in the database -*/ -function ewiki_eventually_initialize(&$id, &$data, &$action) { - - global $USER; - - #-- initialize database only if frontpage missing - if (($id==EWIKI_PAGE_INDEX) && ($action=="edit") && empty($data["version"])) { - - ewiki_database("INIT", array()); -#### BEGIN MOODLE CHANGE - $path=EWIKI_INIT_PAGES; - if (!empty($path)) { - if ($dh = @opendir($path=EWIKI_INIT_PAGES)) { - while (false !== ($filename = readdir($dh))) { -#### MOODLE CHANGE TO SOLVE BUG #3830. Original doesn't support dots in names. - //Orig->if (preg_match('/^(['.EWIKI_CHARS_U.']+['.EWIKI_CHARS_L.']+\w*)+/', $filename)) { - if ($filename == clean_filename($filename) && !is_dir($path.'/'.$filename)) { -#### END OF MOODLE CHANGE TO SOLVE BUG #3830. Original doesn't support dots in names. - $found = ewiki_database("FIND", array($filename)); - if (! $found[$filename]) { - $content = implode("", file("$path/$filename")); - ewiki_scan_wikiwords($content, $ewiki_links, "_STRIP_EMAIL=1"); - $refs = "\n\n" . implode("\n", array_keys($ewiki_links)) . "\n\n"; - $save = array( - "id" => "$filename", - "version" => "1", - "flags" => "1", - "content" => $content, - "author" => ewiki_author("ewiki_initialize"), - "userid" => $USER->id, - "refs" => $refs, - "lastmodified" => filemtime("$path/$filename"), - "created" => filectime("$path/$filename") // (not exact) - ); - ewiki_database("WRITE", $save); - } - } - } - closedir($dh); - } - else { - echo "ewiki error: could not read from directory ". realpath($path) ."
    \n"; - } - } -#### END MOODLE CHANGE - - #-- try to view/ that newly inserted page - if ($data = ewiki_database("GET", array("id"=>$id))) { - $action = "view"; - } - } -} - - - - -#--------------------------------------------------------------------------- - - - -######## ### ######## ### ######## ### ###### ######## -######## ### ######## ### ######## ### ###### ######## -## ## ## ## ## ## ## ## ## ## ## ## ## ## -## ## ## ## ## ## ## ## ## ## ## ## ## ## -## ## ## ## ## ## ## ## ## ## ## ## ## -## ## ## ## ## ## ## ## ## ## ## ## ## -## ## ## ## ## ## ## ######## ## ## ###### ###### -## ## ## ## ## ## ## ######## ## ## ###### ###### -## ## ######### ## ######### ## ## ######### ## ## -## ## ######### ## ######### ## ## ######### ## ## -## ## ## ## ## ## ## ## ## ## ## ## ## ## -## ## ## ## ## ## ## ## ## ## ## ## ## ## -######## ## ## ## ## ## ######## ## ## ###### ######## -######## ## ## ## ## ## ######## ## ## ###### ######## - - - - -/* wrapper -*/ -function ewiki_database($action, $args, $sw1=0, $sw2=0, $pf=false) { - - #-- normalize (fetch bad parameters) - if (($action=="GET") && !is_array($args) && is_string($args)) { - $args = array("id" => $args); - } - - #-- treat special - switch ($action) { - - case "GETALL": - $args = array_unique(@array_merge($args, array("flags", "version"))); - $args = array_diff($args, array("id")); - break; - - case "SEARCH": -# unset($args["version"]); -# unset($args["flags"]); - break; - - default: - break; - } - - #-- handle {meta} sub array as needed - if (is_array(@$args["meta"])) { - $args["meta"] = serialize($args["meta"]); - } - - #-- database plugin - if (($pf) || ($pf = @$GLOBALS["ewiki_plugins"]["database"][0])) { - $r = $pf($action, $args, $sw1, $sw2); - } - else { - ewiki_log("DB layer: no backend!", 0); - $r = false; - } - - #-- database layer generation 2 abstraction - if (is_array($r) && (($action=="SEARCH") || ($action=="GETALL"))) { - $z = new ewiki_dbquery_result(array_keys($args)); - foreach ($r as $id=>$row) { - $z->add($row); - } - $r = $z; - } - - #-- extract {meta} sub array - if (is_array($r) && !is_array(@$r["meta"]) && strlen(@$r["meta"])) { - $r["meta"] = unserialize($r["meta"]); - } - - return($r); -} - - - -/* returned for SEARCH and GETALL queries, as those operations are - otherwise too memory exhaustive -*/ -class ewiki_dbquery_result { - - var $keys = array(); - var $entries = array(); - var $buffer = EWIKI_DBQUERY_BUFFER; - var $size = 0; - - function ewiki_dbquery_result($keys) { - $keys = @array_merge($keys, array(-50=>"id", "version", "flags")); - $this->keys = array_unique($keys); - } - - function add($row) { - if (is_array($row)) { - if ($this->buffer) { - $this->size += strlen(serialize($row)); - $this->buffer = $this->size <= EWIKI_DBQUERY_BUFFER; - } - else { - $row = $row["id"]; - } - } - $this->entries[] = $row; - } - - function get($all=0, $flags=0x00) { - $row = array(); - - $prot_hide = ($flags&0x0020) && EWIKI_PROTECTED_MODE && EWIKI_PROTECTED_MODE_HIDING; - do { - if (count($this->entries)) { - - #-- fetch very first entry from $entries list - $r = array_shift($this->entries); - - #-- finish if buffered entry - if (is_array($r) && !$all) { - $row = $r; - } - #-- else refetch complete entry from database - else { - if (is_array($r)) { - $r = $r["id"]; - } - $r = ewiki_database("GET", array("id"=>$r)); - if (!$all) { - foreach ($this->keys as $key) { - $row[$key] = $r[$key]; - } - } else { - $row = $r; - } - } - unset($r); - } - else { - return(NULL); // no more entries - } - - #-- expand {meta} field - if (is_array($row) && is_string(@$row["meta"])) { - $row["meta"] = unserialize($row["meta"]); - } - - #-- drop unwanted results - if ($prot_hide && !ewiki_auth($row["id"], $row, $ewiki_action)) { - $row = array(); - } - } while ($prot_hide && empty($row)); - - return($row); - } - - function count() { - return(count($this->entries)); - } -} - - - -/* MySQL database backend - (default) - Note: this is of course an abuse of the relational database scheme, - but neccessary for real db independence and abstraction -*/ -function ewiki_database_mysql($action, &$args, $sw1, $sw2) { - - #-- reconnect to the database (if multiple are used) - ## mysql_ping($GLOBALS["db"]); - - #-- result array - $r = array(); - - switch($action) { - - /* Returns database entry as array for the page whose name was given - with the "id" key in the $args array, usually fetches the latest - version of a page, unless a specific "version" was requested in - the $args array. - */ - case "GET": - $id = "'" . mysql_escape_string($args["id"]) . "'"; - ($version = 0 + @$args["version"]) and ($version = "AND (version=$version)") or ($version=""); - $result = mysql_query("SELECT * FROM " . EWIKI_DB_TABLE_NAME - . " WHERE (pagename=$id) $version ORDER BY version DESC LIMIT 1" - ); - if ($result && ($r = mysql_fetch_array($result, MYSQL_ASSOC))) { - $r["id"] = $r["pagename"]; - unset($r["pagename"]); - } - if (strlen($r["meta"])) { - $r["meta"] = @unserialize($r["meta"]); - } - break; - - - - /* Increases the hit counter for the page name given in $args array - with "id" index key. - */ - case "HIT": - mysql_query("UPDATE " . EWIKI_DB_TABLE_NAME . " SET hits=(hits+1) WHERE pagename='" . mysql_escape_string($args["id"]) . "'"); - break; - - - - /* Stores the $data array into the database, while not overwriting - existing entries (using WRITE); returns 0 on failure and 1 if - saved correctly. - */ - case "OVERWRITE": // fall-through - $COMMAND = "REPLACE"; - - case "WRITE": - $args["pagename"] = $args["id"]; - unset($args["id"]); - - if (is_array($args["meta"])) { - $args["meta"] = serialize($args["meta"]); - } - - $sql1 = $sql2 = ""; - foreach ($args as $index => $value) { - if (is_int($index)) { - continue; - } - $a = ($sql1 ? ', ' : ''); - $sql1 .= $a . $index; - $sql2 .= $a . "'" . mysql_escape_string($value) . "'"; - } - - strlen(@$COMMAND) || ($COMMAND = "INSERT"); - - $result = mysql_query("$COMMAND INTO " . EWIKI_DB_TABLE_NAME . - " (" . $sql1 . ") VALUES (" . $sql2 . ")" - ); - - return($result && mysql_affected_rows() ?1:0); - break; - - - - /* Checks for existence of the WikiPages whose names are given in - the $args array. Returns an array with the specified WikiPageNames - associated with values of "0" or "1" (stating if the page exists - in the database). For images/binary db entries returns the "meta" - field instead of an "1". - */ - case "FIND": - $sql = ""; - foreach (array_values($args) as $id) if (strlen($id)) { - $r[$id] = 0; - $sql .= ($sql ? " OR " : "") . - "(pagename='" . mysql_escape_string($id) . "')"; - } - $result = mysql_query($sql = "SELECT pagename AS id, meta FROM " . - EWIKI_DB_TABLE_NAME . " WHERE $sql " - ); - while ($result && ($row = mysql_fetch_row($result))) { - $r[$row[0]] = strpos($row[1], 's:5:"image"') ? $row[1] : 1; - } - break; - - - - /* Returns an array of __all__ pages, where each entry is made up - of the fields from the database requested with the $args array, - e.g. array("flags","meta","lastmodified"); - */ - case "GETALL": - $result = mysql_query("SELECT pagename AS id, ". - implode(", ", $args) . - " FROM ". EWIKI_DB_TABLE_NAME . - " GROUP BY id, version DESC" - ); - $r = new ewiki_dbquery_result($args); - $drop = ""; - while ($result && ($row = mysql_fetch_array($result, MYSQL_ASSOC))) { - $i = EWIKI_CASE_INSENSITIVE ? strtolower($row["id"]) : $row["id"]; - if ($i != $drop) { - $drop = $i; - $r->add($row); - } - } - break; - - - - /* Returns array of database entries (also arrays), where the one - specified column matches the specified content string, for example - $args = array("content" => "text...piece") - is not guaranteed to only search/return the latest version of a page - */ - case "SEARCH": - $field = implode("", array_keys($args)); - $content = strtolower(implode("", $args)); - if ($field == "id") { $field = "pagename"; } - - $result = mysql_query("SELECT pagename AS id, version, flags" . - (EWIKI_DBQUERY_BUFFER && ($field!="pagename") ? ", $field" : "") . - " FROM " . EWIKI_DB_TABLE_NAME . - " WHERE LOCATE('" . mysql_escape_string($content) . "', LCASE($field)) " . - " GROUP BY id, version DESC" - ); - $r = new ewiki_dbquery_result(array("id","version",$field)); - $drop = ""; - while ($result && ($row = mysql_fetch_array($result, MYSQL_ASSOC))) { - $i = EWIKI_CASE_INSENSITIVE ? strtolower($row["id"]) : $row["id"]; - if ($i != $drop) { - $drop = $i; - $r->add($row); - } - } - break; - - - - case "DELETE": - $id = mysql_escape_string($args["id"]); - $version = $args["version"]; - mysql_query("DELETE FROM " . EWIKI_DB_TABLE_NAME ." - WHERE pagename='$id' AND version=$version"); - break; - - - - case "INIT": - mysql_query("CREATE TABLE " . EWIKI_DB_TABLE_NAME ." - (pagename VARCHAR(160) NOT NULL, - version INTEGER UNSIGNED NOT NULL DEFAULT 0, - flags INTEGER UNSIGNED DEFAULT 0, - content MEDIUMTEXT, - author VARCHAR(100) DEFAULT 'ewiki', - userid INTEGER UNSIGNED DEFAULT 0, - created INTEGER UNSIGNED DEFAULT ".time().", - lastmodified INTEGER UNSIGNED DEFAULT 0, - refs MEDIUMTEXT, - meta MEDIUMTEXT, - hits INTEGER UNSIGNED DEFAULT 0, - PRIMARY KEY id (pagename, version) ) - "); - echo mysql_error(); - break; - - default: - } - - return($r); -} - -?> diff --git a/mod/wiki/db/migration/wiki/ewiki/plugins/moodle/moodle_rescue_html.php b/mod/wiki/db/migration/wiki/ewiki/plugins/moodle/moodle_rescue_html.php deleted file mode 100644 index c5e634f76de..00000000000 --- a/mod/wiki/db/migration/wiki/ewiki/plugins/moodle/moodle_rescue_html.php +++ /dev/null @@ -1,45 +0,0 @@ - - (as seen in [sfWiki | http://sfwiki.sf.net/]. - "Safe" tags include Q, S, PRE, TT, H1-H6, KBD, VAR, XMP, B, I - but just see (or change) ewiki_format() for more. They are not - accepted if written with mixed lowercase and uppercase letters, - and they cannot contain any tag attributes. - - RESCUE_HTML was formerly part of the main rendering function, but - has now been extracted into this plugin, so one only needs to - include it to get simple html tags working. -*/ - - -$ewiki_plugins["format_source"][] = "ewiki_moodle_rescue_html"; - - -function ewiki_moodle_rescue_html(&$wiki_source) { - $safe_html = EWIKI_RESCUE_HTML; - $safe_html += 1; - - $rescue_html = array( - "br", "tt", "b", "i", "strong", "em", "s", "kbd", "var", "xmp", "sup", "sub", - "pre", "q", "h1", "h2", "h3", "h4", "h5", "h6", "cite", "code", "u", - ); - - - - #-- unescape allowed html - if ($safe_html) { - /* - foreach ($rescue_html as $tag) { - foreach(array($tag, "/$tag", ($tag=strtoupper($tag)), "/$tag") as $tag) { - $wiki_source = str_replace('<'.$tag.'>', "<".$tag.">", $wiki_source); - } } - */ - $regexp='#<(/?('.implode("|",$rescue_html).'))( /)?>#i'; - $wiki_source = preg_replace($regexp, '<$1>', $wiki_source); - } - -} - diff --git a/mod/wiki/db/migration/wiki/ewikimoodlelib.php b/mod/wiki/db/migration/wiki/ewikimoodlelib.php deleted file mode 100644 index abb0da763dd..00000000000 --- a/mod/wiki/db/migration/wiki/ewikimoodlelib.php +++ /dev/null @@ -1,316 +0,0 @@ -pagename); COMMENTED BY PIGUI BECOUSE OF MIGRATION - -define("EWIKI_CONTROL_LINE", 0); -define("EWIKI_LIST_LIMIT", 25); -//define("EWIKI_DEFAULT_LANG", current_language()); COMMENTED BY PIGUI BECOUSE OF MIGRATION -define("EWIKI_HTML_CHARS", 1); -define("EWIKI_DB_TABLE_NAME", "wiki_pages_old"); - - -function ewiki_database_moodle($action, &$args, $sw1, $sw2) { - global $wiki, $wiki_entry, $CFG, $DB; - #-- result array - $r = array(); - - switch($action) { - - /* Returns database entry as array for the page whose name was given - with the "id" key in the $args array, usually fetches the latest - version of a page, unless a specific "version" was requested in - the $args array. - */ - # Ugly, but we need to choose which wiki we are about to change/read - case "GET": - $params = array('id'=>$args["id"]); - if ($version = 0 + @$args["version"]) { - $params['version'] = $version; - $versionsql = "AND version = :version"; - } else { - $versionsql = ""; - - } - - # $result = mysql_query("SELECT * FROM " . EWIKI_DB_TABLE_NAME - # . " WHERE (pagename=$id) $version ORDER BY version DESC LIMIT 1" - #); - #if ($result && ($r = mysql_fetch_array($result, MYSQL_ASSOC))) { - # $r["id"] = $r["pagename"]; - # unset($r["pagename"]); - #} - #if (strlen($r["meta"])) { - # $r["meta"] = @unserialize($r["meta"]); - #} - - $select="(pagename=:id) AND wiki= :weid $versionsql "; - $params['weid'] = $wiki_entry->id; - $sort="version DESC"; - - if ($result_arr = $DB->get_records_select(EWIKI_DB_TABLE_NAME, $select, $params, $sort,"*",0,1)) { - //Iterate to get the first (and unique!) - foreach ($result_arr as $obj) { - $result_obj = $obj; - } - } - if($result_obj) { - //Convert to array - $r=get_object_vars($result_obj); - $r["id"] = $r["pagename"]; - unset($r["pagename"]); - $r["meta"] = @unserialize($r["meta"]); - } - break; - - - - /* Increases the hit counter for the page name given in $args array - with "id" index key. - */ - case "HIT": - #mysql_query("UPDATE " . EWIKI_DB_TABLE_NAME . " SET hits=(hits+1) WHERE pagename='" . anydb_escape_string($args["id"]) . "'"); - # $DB->set_field does not work because of the "hits+1" construct - #print "DO ".anydb__escape_string($args["id"]); exit; - $DB->execute("UPDATE {".EWIKI_DB_TABLE_NAME."} SET hits=(hits+1) WHERE pagename=? and wiki=?", array($args["id"], $wiki_entry->id)); - break; - /* Stores the $data array into the database, while not overwriting - existing entries (using WRITE); returns 0 on failure and 1 if - saved correctly. - */ - case "OVERWRITE": - $COMMAND = "REPLACE"; - break; - - case "WRITE": - $COMMAND="WRITE"; - $args["pagename"] = $args["id"]; - unset($args["id"]); - - if (is_array($args["meta"])) { - $args["meta"] = serialize($args["meta"]); - } - - #$sql1 = $sql2 = ""; - #foreach ($args as $index => $value) { - # if (is_int($index)) { - # continue; - # } - # $a = ($sql1 ? ', ' : ''); - # $sql1 .= $a . $index; - # $sql2 .= $a . "'" . anydb_escape_string($value) . "'"; - #} - - #strlen(@$COMMAND) || ($COMMAND = "INSERT"); - - foreach ($args as $index => $value) { - if (is_int($index)) { - continue; - } - $args[$index] =anydb_escape_string($value); - } - $args["wiki"]=$wiki_entry->id; - - # Check if Record exists - if($COMMAND=="REPLACE") { - if ($DB->count_records(EWIKI_DB_TABLE_NAME, array("wiki"=>$wiki_entry->id,"pagename"=>$args["pagename"],"version"=>$args["version"]))) { - $DB->delete_record(EWIKI_DB_TABLE_NAME, array("wiki"=>$wiki_entry->id,"pagename"=>$args["pagename"],"version"=>$args["version"])); - } - } - - # Write - $result=$DB->insert_record(EWIKI_DB_TABLE_NAME,(object)$args,false); - - #$result = mysql_query("$COMMAND INTO " . EWIKI_DB_TABLE_NAME . - # " (" . $sql1 . ") VALUES (" . $sql2 . ")" - #); - #return($result && mysql_affected_rows() ?1:0); - - return $result; - break; - - - - /* Checks for existence of the WikiPages whose names are given in - the $args array. Returns an array with the specified WikiPageNames - associated with values of "0" or "1" (stating if the page exists - in the database). For images/binary db entries returns the "meta" - field instead of an "1". - */ - case "FIND": - $select = ""; - $params = array(); - $p=0; - foreach (array_values($args) as $id) { - if (strlen($id)) { - $p++; - $pname = "par$p"; - $r[$id] = 0; - $select .= ($select ? " OR " : "") . - "(pagename= :$pname)"; - $params[$pname] = $id; - } - } - if($select) { - $select = "(".$select.") AND wiki= :weid "; - $params['weid'] = $wiki_entry->id; - $result = $DB->get_records_select(EWIKI_DB_TABLE_NAME,$select, $params); - - while(list($key, $val) = @each($result)) { - $r[$val->pagename]=strpos($val->meta, 's:5:"image"') ? $val->meta : 1; - } - } - break; - - /* Counts the number of Versions - */ - case "COUNTVERSIONS": - $sql= "SELECT pagename AS id, count(*) as versioncount". - " FROM {".EWIKI_DB_TABLE_NAME."} - WHERE wiki = ?". - " GROUP BY pagename"; - - #print "$sql"; - $result=$DB->get_records_sql($sql, array($wiki_entry->id)); - while(list($key, $val) = each($result)) { - $r[$key]=$val->versioncount; - } - break; - - /* Returns an array of the lastest versions of __all__ pages, - where each entry is made up of the fields from the database - requested with the $args array, e.g. - array("flags","meta","lastmodified"); - */ - case "GETALL": - switch ($DB->get_db_family()) { - case 'postgres': - // All but the latest version eliminated by DISTINCT - // ON (pagename) - $sql= "SELECT DISTINCT ON (pagename) pagename AS id, ". - implode(", ", $args) . - " FROM {".EWIKI_DB_TABLE_NAME."}". - " WHERE wiki = ?". - " ORDER BY pagename, version DESC"; - break; - case 'mysql': - // All but the latest version eliminated by - // mysql-specific GROUP BY-semantics - $sql= "SELECT pagename AS id, ". - implode(", ", $args) . - " FROM {".EWIKI_DB_TABLE_NAME."}". - " WHERE wiki = ?". - " GROUP BY id, version DESC " ; - default: - // All but the latest version are here eliminated in - // $DB->get_records_sql, since it will return an array - // with only one result per id-field value. Note, - // that for this to work the query needs to order the - // records ascending by version, so later versions - // will overwrite previous ones in - // recordset_to_array. This is not pretty. - $sql= "SELECT pagename AS id, ". - implode(", ", $args) . - " FROM {".EWIKI_DB_TABLE_NAME."}". - " WHERE wiki = ?". - " ORDER BY version"; - } - - $result = $DB->get_records_sql($sql, array($wiki_entry->id)); - $r = new ewiki_dbquery_result($args); - - if ($result) { - foreach($result as $val) { - $r->add(get_object_vars($val)); - } - } - - break; - - - - /* Returns array of database entries (also arrays), where the one - specified column matches the specified content string, for example - $args = array("content" => "text...piece") - is not guaranteed to only search/return the latest version of a page - */ - case "SEARCH": - $field = implode("", array_keys($args)); - $content = strtolower(implode("", $args)); - if ($field == "id") { $field = "pagename"; } - $sql= "SELECT pagename AS id, version, flags" . - (EWIKI_DBQUERY_BUFFER && ($field!="pagename") ? ", $field" : "") . - " FROM {".EWIKI_DB_TABLE_NAME."}". - " WHERE " . $DB->sql_like($field, '?', false) . " and wiki= ?". - " ORDER BY id, version ASC"; - $result=$DB->get_records_sql($sql, array("%$content%", $wiki_entry->id)); - - $r = new ewiki_dbquery_result(array("id","version",$field)); - $drop = ""; - #while ($result && ($row = mysql_fetch_array($result, MYSQL_ASSOC))) { - # $i = EWIKI_CASE_INSENSITIVE ? strtolower($row["id"]) : $row["id"]; - # if ($i != $drop) { - # $drop = $i; - # $r->add($row); - # } - #} - while(list($key, $val) = @each($result)) { - $row=get_object_vars($val); - $i = EWIKI_CASE_INSENSITIVE ? strtolower($row["id"]) : $row["id"]; - if ($i != $drop) { - $drop = $i; - $r->add($row); - } - } - break; - - - case "DELETE": - $id = $args["id"]; - $version = $args["version"]; - - #mysql_query("DELETE FROM " . EWIKI_DB_TABLE_NAME ." - # WHERE pagename='$id' AND version=$version"); - # print "DELETING wiki:".$wiki_entry->id."Pagename: $id Version: $version
    \n"; - $DB->delete_records(EWIKI_DB_TABLE_NAME, array("wiki"=>$wiki_entry->id,"pagename"=>$id,"version"=>$version)); - - break; - - - - case "INIT": - #mysql_query("CREATE TABLE " . EWIKI_DB_TABLE_NAME ." - # (pagename VARCHAR(160) NOT NULL, - # version INTEGER UNSIGNED NOT NULL DEFAULT 0, - # flags INTEGER UNSIGNED DEFAULT 0, - # content MEDIUMTEXT, - # author VARCHAR(100) DEFAULT 'ewiki', - # created INTEGER UNSIGNED DEFAULT ".time().", - # lastmodified INTEGER UNSIGNED DEFAULT 0, - # refs MEDIUMTEXT, - # meta MEDIUMTEXT, - # hits INTEGER UNSIGNED DEFAULT 0, - # PRIMARY KEY id (pagename, version) ) - # "); - #echo mysql_error(); - break; - - default: - } - - return($r); -} - -function anydb_escape_string($s) { - return($s); -} - diff --git a/mod/wiki/db/upgrade.php b/mod/wiki/db/upgrade.php index d4c84b6c630..c8ac21847d2 100644 --- a/mod/wiki/db/upgrade.php +++ b/mod/wiki/db/upgrade.php @@ -41,337 +41,6 @@ function xmldb_wiki_upgrade($oldversion) { $dbman = $DB->get_manager(); - // Step 0: Add new fields to main wiki table - if ($oldversion < 2010040100) { - require_once(dirname(__FILE__) . '/upgradelib.php'); - echo $OUTPUT->notification('Adding new fields to wiki table', 'notifysuccess'); - wiki_add_wiki_fields(); - - upgrade_mod_savepoint(true, 2010040100, 'wiki'); - } - - // Step 1: Rename old tables - if ($oldversion < 2010040101) { - $tables = array('wiki_pages', 'wiki_locks', 'wiki_entries'); - - echo $OUTPUT->notification('Renaming old wiki module tables', 'notifysuccess'); - foreach ($tables as $tablename) { - $table = new xmldb_table($tablename); - if ($dbman->table_exists($table)) { - if ($dbman->table_exists($table)) { - $dbman->rename_table($table, $tablename . '_old'); - } - } - } - upgrade_mod_savepoint(true, 2010040101, 'wiki'); - } - - // Step 2: Creating new tables - if ($oldversion < 2010040102) { - require_once(dirname(__FILE__) . '/upgradelib.php'); - echo $OUTPUT->notification('Installing new wiki module tables', 'notifysuccess'); - wiki_upgrade_install_20_tables(); - upgrade_mod_savepoint(true, 2010040102, 'wiki'); - } - - // Step 3: migrating wiki instances - if ($oldversion < 2010040103) { - upgrade_set_timeout(); - - // Setting up wiki configuration - $sql = "UPDATE {wiki} - SET intro = summary, - firstpagetitle = pagename, - defaultformat = ?"; - $DB->execute($sql, array('html')); - - $sql = "UPDATE {wiki} - SET wikimode = ? - WHERE wtype = ?"; - $DB->execute($sql, array('collaborative', 'group')); - - $sql = "UPDATE {wiki} - SET wikimode = ? - WHERE wtype != ?"; - $DB->execute($sql, array('individual', 'group')); - - // Removing edit & create capability to students in old teacher wikis - $studentroles = $DB->get_records('role', array('archetype' => 'student')); - $wikis = $DB->get_records('wiki'); - foreach ($wikis as $wiki) { - echo $OUTPUT->notification('Migrating '.$wiki->wtype.' type wiki instance: '.$wiki->name, 'notifysuccess'); - if ($wiki->wtype == 'teacher') { - $cm = get_coursemodule_from_instance('wiki', $wiki->id); - $context = get_context_instance(CONTEXT_MODULE, $cm->id); - foreach ($studentroles as $studentrole) { - role_change_permission($studentrole->id, $context, 'mod/wiki:editpage', CAP_PROHIBIT); - role_change_permission($studentrole->id, $context, 'mod/wiki:createpage', CAP_PROHIBIT); - } - } - } - - echo $OUTPUT->notification('Migrating old wikis to new wikis', 'notifysuccess'); - upgrade_mod_savepoint(true, 2010040103, 'wiki'); - } - - // Step 4: migrating wiki entries to new subwikis - if ($oldversion < 2010040104) { - /** - * Migrating wiki entries to new subwikis - */ - $sql = "INSERT INTO {wiki_subwikis} (wikiid, groupid, userid) - SELECT DISTINCT e.wikiid, e.groupid, e.userid - FROM {wiki_entries_old} e"; - echo $OUTPUT->notification('Migrating old entries to new subwikis', 'notifysuccess'); - - $DB->execute($sql, array()); - - upgrade_mod_savepoint(true, 2010040104, 'wiki'); - } - - // Step 5: Migrating pages - if ($oldversion < 2010040105) { - - // select all wiki pages - $sql = "SELECT s.id, p.pagename, p.created, p.lastmodified, p.userid, p.hits - FROM {wiki_pages_old} p - LEFT OUTER JOIN {wiki_entries_old} e ON e.id = p.wiki - LEFT OUTER JOIN {wiki_subwikis} s ON s.wikiid = e.wikiid AND s.groupid = e.groupid AND s.userid = e.userid - WHERE p.version = (SELECT max(po.version) - FROM {wiki_pages_old} po - WHERE p.pagename = po.pagename AND p.wiki = po.wiki)"; - echo $OUTPUT->notification('Migrating old pages to new pages', 'notifysuccess'); - - $records = $DB->get_recordset_sql($sql); - foreach ($records as $record) { - $page = new stdclass(); - $page->subwikiid = $record->id; - $page->title = $record->pagename; - $page->cachedcontent = '**reparse needed**'; - $page->timecreated = $record->created; - $page->timemodified = $record->lastmodified; - $page->userid = $record->userid; - $page->pageviews = $record->hits; - try { - // make sure there is no duplicated records exist - if (!$DB->record_exists('wiki_pages', array('subwikiid'=>$record->id, 'userid'=>$record->userid, 'title'=>$record->pagename))) { - $DB->insert_record('wiki_pages', $page); - } - } catch (dml_exception $e) { - // catch possible insert exception - debugging($e->getMessage()); - continue; - } - } - $records->close(); - - upgrade_mod_savepoint(true, 2010040105, 'wiki'); - } - - // Step 6: Migrating versions - if ($oldversion < 2010040106) { - require_once(dirname(__FILE__) . '/upgradelib.php'); - echo $OUTPUT->notification('Migrating old history to new history', 'notifysuccess'); - wiki_upgrade_migrate_versions(); - upgrade_mod_savepoint(true, 2010040106, 'wiki'); - } - - // Step 7: refresh cachedcontent and fill wiki links table - if ($oldversion < 2010040107) { - require_once($CFG->dirroot. '/mod/wiki/locallib.php'); - upgrade_set_timeout(); - - $pages = $DB->get_recordset('wiki_pages'); - - foreach ($pages as $page) { - wiki_refresh_cachedcontent($page); - } - - $pages->close(); - - echo $OUTPUT->notification('Caching content', 'notifysuccess'); - upgrade_mod_savepoint(true, 2010040107, 'wiki'); - } - // Step 8, migrating files - if ($oldversion < 2010040108) { - $fs = get_file_storage(); - $sql = "SELECT files.*, po.meta AS filemeta FROM {wiki_pages_old} po JOIN ( - SELECT DISTINCT po.id, po.pagename, w.id AS wikiid, po.userid, - eo.id AS entryid, eo.groupid, s.id AS subwiki, - w.course AS courseid, cm.id AS cmid - FROM {wiki_pages_old} po - LEFT OUTER JOIN {wiki_entries_old} eo - ON eo.id=po.wiki - LEFT OUTER JOIN {wiki} w - ON w.id = eo.wikiid - LEFT OUTER JOIN {wiki_subwikis} s - ON s.groupid = eo.groupid AND s.wikiid = eo.wikiid AND eo.userid = s.userid - JOIN {modules} m ON m.name = 'wiki' - JOIN {course_modules} cm ON (cm.module = m.id AND cm.instance = w.id) - ) files ON files.id = po.id"; - - $rs = $DB->get_recordset_sql($sql); - foreach ($rs as $r) { - if (strpos($r->pagename, 'internal://') !== false) { - // Found a file resource! - $pattern = 'internal://'; - $matches = array(); - $filename = str_replace($pattern, '', $r->pagename); - $orgifilename = $filename = clean_param($filename, PARAM_FILE); - $context = get_context_instance(CONTEXT_MODULE, $r->cmid); - $filemeta = unserialize($r->filemeta); - $filesection = $filemeta['section']; - // When attach a file to wiki page, user can customize the file name instead of original file name - // if user did, old wiki will create two pages, internal://original_pagename and internal://renamed_pagename - // internal://original_pagename record has renamed pagename in meta field - // but all file have this field - // old wiki will rename file names to filter space and special character - if (!empty($filemeta['Content-Location'])) { - $orgifilename = urldecode($filemeta['Content-Location']); - $orgifilename = str_replace(' ', '_', $orgifilename); - } - $thefile = $CFG->dataroot . '/' . $r->courseid . '/moddata/wiki/' . $r->wikiid .'/' . $r->entryid . '/'. $filesection .'/'. $filename; - - if (is_file($thefile) && is_readable($thefile)) { - $filerecord = array('contextid' => $context->id, - 'component' => 'mod_wiki', - 'filearea' => 'attachments', - 'itemid' => $r->subwiki, - 'filepath' => '/', - 'filename' => $orgifilename, - 'userid' => $r->userid); - if (!$fs->file_exists($context->id, 'mod_wiki', 'attachments', $r->subwiki, '/', $orgifilename)) { - //echo $OUTPUT->notification('Migrating file '.$orgifilename, 'notifysuccess'); - $storedfile = $fs->create_file_from_pathname($filerecord, $thefile); - } - // we have to create another file here to make sure interlinks work - if (!$fs->file_exists($context->id, 'mod_wiki', 'attachments', $r->subwiki, '/', $filename)) { - $filerecord['filename'] = $filename; - //echo $OUTPUT->notification('Migrating file '.$filename, 'notifysuccess'); - $storedfile = $fs->create_file_from_pathname($filerecord, $thefile); - } - } else { - echo $OUTPUT->notification("Bad data found: $r->pagename
    Expected file path: $thefile Please fix the bad file path manually."); - } - } - } - $rs->close(); - upgrade_mod_savepoint(true, 2010040108, 'wiki'); - } - - // Step 9: clean wiki table - if ($oldversion < 2010040109) { - $fields = array('summary', 'pagename', 'wtype', 'ewikiprinttitle', 'htmlmode', 'ewikiacceptbinary', 'disablecamelcase', 'setpageflags', 'strippages', 'removepages', 'revertchanges', 'initialcontent'); - $table = new xmldb_table('wiki'); - foreach ($fields as $fieldname) { - $field = new xmldb_field($fieldname); - if ($dbman->field_exists($table, $field)) { - $dbman->drop_field($table, $field); - } - - } - echo $OUTPUT->notification('Cleaning wiki table', 'notifysuccess'); - upgrade_mod_savepoint(true, 2010040109, 'wiki'); - } - - if ($oldversion < 2010080201) { - - $sql = "UPDATE {comments} - SET commentarea = 'wiki_page' - WHERE commentarea = 'wiki_comment_section'"; - $DB->execute($sql); - - $sql = "UPDATE {tag_instance} - SET itemtype = 'wiki_page' - WHERE itemtype = 'wiki'"; - $DB->execute($sql); - - echo $OUTPUT->notification('Updating comments and tags', 'notifysuccess'); - - upgrade_mod_savepoint(true, 2010080201, 'wiki'); - } - - if ($oldversion < 2010102500) { - - // Define key subwikifk (foreign) to be added to wiki_pages - $table = new xmldb_table('wiki_pages'); - $key = new xmldb_key('subwikifk', XMLDB_KEY_FOREIGN, array('subwikiid'), 'wiki_subwikis', array('id')); - - // Launch add key subwikifk - $dbman->add_key($table, $key); - - // Define key subwikifk (foreign) to be added to wiki_links - $table = new xmldb_table('wiki_links'); - $key = new xmldb_key('subwikifk', XMLDB_KEY_FOREIGN, array('subwikiid'), 'wiki_subwikis', array('id')); - - // Launch add key subwikifk - $dbman->add_key($table, $key); - - // wiki savepoint reached - upgrade_mod_savepoint(true, 2010102500, 'wiki'); - } - - if ($oldversion < 2010102800) { - - $sql = "UPDATE {tag_instance} - SET itemtype = 'wiki_pages' - WHERE itemtype = 'wiki_page'"; - $DB->execute($sql); - - echo $OUTPUT->notification('Updating tags itemtype', 'notifysuccess'); - - upgrade_mod_savepoint(true, 2010102800, 'wiki'); - } - - if ($oldversion < 2011011000) { - // Fix wiki in the post table after upgrade from 1.9 - $table = new xmldb_table('wiki'); - - // name should default to Wiki - $field = new xmldb_field('name', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL, null, 'Wiki', 'course'); - if ($dbman->field_exists($table, $field)) { - $dbman->change_field_default($table, $field); - } - - // timecreated field is missing after 1.9 upgrade - $field = new xmldb_field('timecreated', XMLDB_TYPE_INTEGER, 10, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, 0, 'introformat'); - if (!$dbman->field_exists($table, $field)) { - $dbman->add_field($table, $field); - } - - // timemodified field is missing after 1.9 upgrade - $field = new xmldb_field('timemodified', XMLDB_TYPE_INTEGER, 10, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, 0, 'timecreated'); - if (!$dbman->field_exists($table, $field)) { - $dbman->add_field($table, $field); - } - - // scaleid is not there any more - $field = new xmldb_field('scaleid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', null); - if ($dbman->field_exists($table, $field)) { - $dbman->drop_field($table, $field); - } - - upgrade_mod_savepoint(true, 2011011000, 'wiki'); - } - - // TODO: Will hold the old tables so we will have chance to fix problems - // Will remove old tables once migrating 100% stable - // Step 10: delete old tables - //if ($oldversion < 2011060300) { - //$tables = array('wiki_pages', 'wiki_locks', 'wiki_entries'); - - //foreach ($tables as $tablename) { - //$table = new xmldb_table($tablename . '_old'); - //if ($dbman->table_exists($table)) { - //$dbman->drop_table($table); - //} - //} - //echo $OUTPUT->notification('Droping old tables', 'notifysuccess'); - //upgrade_mod_savepoint(true, 2011060300, 'wiki'); - //} - - // 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 diff --git a/mod/wiki/db/upgradelib.php b/mod/wiki/db/upgradelib.php deleted file mode 100644 index 1fd3d44fc37..00000000000 --- a/mod/wiki/db/upgradelib.php +++ /dev/null @@ -1,338 +0,0 @@ -. - -/** - * @package mod-wiki - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ - -function wiki_add_wiki_fields() { - global $DB; - - upgrade_set_timeout(); - $dbman = $DB->get_manager(); - /// Define table wiki to be created - $table = new xmldb_table('wiki'); - - // Adding fields to wiki table - $wikitable = new xmldb_table('wiki'); - - // in MOODLE_20_SABLE branch, summary field is renamed as intro - // so we renamed it back to summary to keep upgrade going as moodle 1.9 - $field = new xmldb_field('intro', XMLDB_TYPE_TEXT, 'medium', null, null, null, null, null); - if ($dbman->field_exists($wikitable, $field)) { - $dbman->rename_field($wikitable, $field, 'summary'); - } - $dbman->add_field($wikitable, $field); - - $field = new xmldb_field('introformat', XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', null); - if (!$dbman->field_exists($wikitable, $field)) { - $dbman->add_field($wikitable, $field); - } - - $field = new xmldb_field('firstpagetitle', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, 'First Page', null); - $dbman->add_field($wikitable, $field); - - $field = new xmldb_field('wikimode', XMLDB_TYPE_CHAR, '20', null, XMLDB_NOTNULL, null, 'collaborative', null); - $dbman->add_field($wikitable, $field); - - $field = new xmldb_field('defaultformat', XMLDB_TYPE_CHAR, '20', null, XMLDB_NOTNULL, null, 'creole', null); - $dbman->add_field($wikitable, $field); - - $field = new xmldb_field('forceformat', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '1', null); - $dbman->add_field($wikitable, $field); - - $field = new xmldb_field('scaleid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', null); - $dbman->add_field($wikitable, $field); - - $field = new xmldb_field('editbegin', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', null); - $dbman->add_field($wikitable, $field); - - $field = new xmldb_field('editend', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, '0', null); - $dbman->add_field($wikitable, $field); - -} - -/** - * Install wiki 2.0 tables - */ -function wiki_upgrade_install_20_tables() { - global $DB; - upgrade_set_timeout(); - $dbman = $DB->get_manager(); - - /// Define table wiki_subwikis to be created - $table = new xmldb_table('wiki_subwikis'); - - /// Adding fields to table wiki_subwikis - $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); - $table->add_field('wikiid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); - $table->add_field('groupid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); - $table->add_field('userid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); - - /// Adding keys to table wiki_subwikis - $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); - $table->add_key('wikiidgroupiduserid', XMLDB_KEY_UNIQUE, array('wikiid', 'groupid', 'userid')); - $table->add_key('wikifk', XMLDB_KEY_FOREIGN, array('wikiid'), 'wiki', array('id')); - - /// Conditionally launch create table for wiki_subwikis - if (!$dbman->table_exists($table)) { - $dbman->create_table($table); - } - - /// Define table wiki_pages to be created - $table = new xmldb_table('wiki_pages'); - - /// Adding fields to table wiki_pages - $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); - $table->add_field('subwikiid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); - $table->add_field('title', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, 'title'); - $table->add_field('cachedcontent', XMLDB_TYPE_TEXT, 'medium', null, XMLDB_NOTNULL, null, null); - $table->add_field('timecreated', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); - $table->add_field('timemodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); - $table->add_field('timerendered', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); - $table->add_field('userid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); - $table->add_field('pageviews', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); - $table->add_field('readonly', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); - - /// Adding keys to table wiki_pages - $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); - $table->add_key('subwikititleuser', XMLDB_KEY_UNIQUE, array('subwikiid', 'title', 'userid')); - $table->add_key('subwikifk', XMLDB_KEY_FOREIGN, array('subwikiid'), 'wiki_subwiki', array('id')); - - /// Conditionally launch create table for wiki_pages - if (!$dbman->table_exists($table)) { - $dbman->create_table($table); - } - - /// Define table wiki_versions to be created - $table = new xmldb_table('wiki_versions'); - - /// Adding fields to table wiki_versions - $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); - $table->add_field('pageid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); - $table->add_field('content', XMLDB_TYPE_TEXT, 'medium', null, XMLDB_NOTNULL, null, null); - $table->add_field('contentformat', XMLDB_TYPE_CHAR, '20', null, XMLDB_NOTNULL, null, 'creole'); - $table->add_field('version', XMLDB_TYPE_INTEGER, '5', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); - $table->add_field('timecreated', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); - $table->add_field('userid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); - - /// Adding keys to table wiki_versions - $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); - $table->add_key('pagefk', XMLDB_KEY_FOREIGN, array('pageid'), 'wiki_pages', array('id')); - - /// Conditionally launch create table for wiki_versions - if (!$dbman->table_exists($table)) { - $dbman->create_table($table); - } - - /// Define table wiki_synonyms to be created - $table = new xmldb_table('wiki_synonyms'); - - /// Adding fields to table wiki_synonyms - $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); - $table->add_field('subwikiid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); - $table->add_field('pageid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); - $table->add_field('pagesynonym', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, 'Pagesynonym'); - - /// Adding keys to table wiki_synonyms - $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); - $table->add_key('pageidsyn', XMLDB_KEY_UNIQUE, array('pageid', 'pagesynonym')); - - /// Conditionally launch create table for wiki_synonyms - if (!$dbman->table_exists($table)) { - $dbman->create_table($table); - } - - /// Define table wiki_links to be created - $table = new xmldb_table('wiki_links'); - - /// Adding fields to table wiki_links - $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); - $table->add_field('subwikiid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); - $table->add_field('frompageid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); - $table->add_field('topageid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); - $table->add_field('tomissingpage', XMLDB_TYPE_CHAR, '255', null, null, null, null); - - /// Adding keys to table wiki_links - $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); - $table->add_key('frompageidfk', XMLDB_KEY_FOREIGN, array('frompageid'), 'wiki_pages', array('id')); - $table->add_key('subwikifk', XMLDB_KEY_FOREIGN, array('subwikiid'), 'wiki_subwiki', array('id')); - - /// Conditionally launch create table for wiki_links - if (!$dbman->table_exists($table)) { - $dbman->create_table($table); - } - - /// Define table wiki_locks to be created - $table = new xmldb_table('wiki_locks'); - - /// Adding fields to table wiki_locks - $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); - $table->add_field('pageid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); - $table->add_field('sectionname', XMLDB_TYPE_CHAR, '255', null, null, null, null); - $table->add_field('userid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); - $table->add_field('lockedat', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); - - /// Adding keys to table wiki_locks - $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); - - /// Conditionally launch create table for wiki_locks - if (!$dbman->table_exists($table)) { - $dbman->create_table($table); - } -} - -/** - * Migrating wiki pages history - */ -function wiki_upgrade_migrate_versions() { - global $DB, $CFG, $OUTPUT; - require_once($CFG->dirroot . '/mod/wiki/db/migration/lib.php'); - // need to move the binary data in db - $fs = get_file_storage(); - // select all wiki pages history - $sql = "SELECT po.id AS oldpage_id, po.pagename AS oldpage_pagename, po.version, po.flags, - po.content, po.author, po.userid AS oldpage_userid, po.created, po.lastmodified, po.refs, po.meta, po.hits, po.wiki, - p.id AS newpage_id, p.subwikiid, p.title, p.cachedcontent, p.timecreated, p.timemodified AS newpage_timemodified, - p.timerendered, p.userid AS newpage_userid, p.pageviews, p.readonly, e.id AS entry_id, e.wikiid, e.course AS entrycourse, - e.groupid, e.userid AS entry_userid, e.pagename AS entry_pagename, e.timemodified AS entry_timemodified, - w.id AS wiki_id, w.course AS wiki_course, w.name, w.summary AS summary, w.pagename AS wiki_pagename, w.wtype, - w.ewikiprinttitle, w.htmlmode, w.ewikiacceptbinary, w.disablecamelcase, w.setpageflags, w.strippages, w.removepages, - w.revertchanges, w.initialcontent, w.timemodified AS wiki_timemodified, - cm.id AS cmid - FROM {wiki_pages_old} po - LEFT OUTER JOIN {wiki_entries_old} e ON e.id = po.wiki - LEFT OUTER JOIN {wiki} w ON w.id = e.wikiid - LEFT OUTER JOIN {wiki_subwikis} s ON e.groupid = s.groupid AND e.wikiid = s.wikiid AND e.userid = s.userid - LEFT OUTER JOIN {wiki_pages} p ON po.pagename = p.title AND p.subwikiid = s.id - JOIN {modules} m ON m.name = 'wiki' - JOIN {course_modules} cm ON (cm.module = m.id AND cm.instance = w.id)"; - - $pagesinfo = $DB->get_recordset_sql($sql, array()); - - foreach ($pagesinfo as $pageinfo) { - upgrade_set_timeout(); - - $mimetype = ewiki_mime_magic($pageinfo->content); - if (!empty($mimetype)) { - // if mimetype is not empty, means this is a file stored in db - $context = get_context_instance(CONTEXT_MODULE, $pageinfo->cmid); - // clean up file name - $filename = clean_param($pageinfo->oldpage_pagename, PARAM_FILE); - $filerecord = array('contextid' => $context->id, - 'component' => 'mod_wiki', - 'filearea' => 'attachments', - 'itemid' => $pageinfo->subwikiid, - 'filepath' => '/', - 'filename' => $filename, - 'userid' => $pageinfo->oldpage_userid); - if (!$fs->file_exists($context->id, 'mod_wiki', 'attachments', $pageinfo->subwikiid, '/', $pageinfo->pagename)) { - $storedfile = $fs->create_file_from_string($filerecord, $pageinfo->content); - } - - // replace page content to a link point to the file - $pageinfo->content = "$pageinfo->oldpage_pagename"; - } - - $oldpage = new StdClass(); - $oldpage->id = $pageinfo->oldpage_id; - $oldpage->pagename = $pageinfo->oldpage_pagename; - $oldpage->version = $pageinfo->version; - $oldpage->flags = $pageinfo->flags; - $oldpage->content = $pageinfo->content; - $oldpage->author = $pageinfo->author; - $oldpage->userid = $pageinfo->oldpage_userid; - $oldpage->created = $pageinfo->created; - $oldpage->lastmodified = $pageinfo->lastmodified; - $oldpage->refs = $pageinfo->refs; - $oldpage->meta = $pageinfo->meta; - $oldpage->hits = $pageinfo->hits; - $oldpage->wiki = $pageinfo->wiki; - - $page = new StdClass(); - $page->id = $pageinfo->newpage_id; - $page->subwikiid = $pageinfo->subwikiid; - $page->title = $pageinfo->title; - $page->cachedcontent = $pageinfo->cachedcontent; - $page->timecreated = $pageinfo->timecreated; - $page->timemodified = $pageinfo->newpage_timemodified; - $page->timerendered = $pageinfo->timerendered; - $page->userid = $pageinfo->newpage_userid; - $page->pageviews = $pageinfo->pageviews; - $page->readonly = $pageinfo->readonly; - - $entry = new StdClass(); - $entry->id = $pageinfo->entry_id; - $entry->wikiid = $pageinfo->wikiid; - $entry->course = $pageinfo->entrycourse; - $entry->groupid = $pageinfo->groupid; - $entry->userid = $pageinfo->entry_userid; - $entry->pagename = $pageinfo->entry_pagename; - $entry->timemodified = $pageinfo->entry_timemodified; - - $wiki = new StdClass(); - $wiki->id = $pageinfo->wiki_id; - $wiki->course = $pageinfo->wiki_course; - $wiki->name = $pageinfo->name; - $wiki->summary = $pageinfo->summary; - $wiki->pagename = $pageinfo->wiki_pagename; - $wiki->wtype = $pageinfo->wtype; - $wiki->ewikiprinttitle = $pageinfo->ewikiprinttitle; - $wiki->htmlmode = $pageinfo->htmlmode; - $wiki->ewikiacceptbinary = $pageinfo->ewikiacceptbinary; - $wiki->disablecamelcase = $pageinfo->disablecamelcase; - $wiki->setpageflags = $pageinfo->setpageflags; - $wiki->strippages = $pageinfo->strippages; - $wiki->removepages = $pageinfo->removepages; - $wiki->revertchanges = $pageinfo->revertchanges; - $wiki->initialcontent = $pageinfo->initialcontent; - $wiki->timemodified = $pageinfo->wiki_timemodified; - - $version = new StdClass(); - $version->pageid = $page->id; - // convert wiki content to html format - $version->content = wiki_ewiki_2_html($entry, $oldpage, $wiki); - $version->contentformat = 'html'; - $version->version = $oldpage->version; - $version->timecreated = $oldpage->lastmodified; - $version->userid = $oldpage->userid; - if ($version->version == 1) { - // The oldest version of page in moodle 2.0 is 0 which has empty content - // so we need to insert an extra record - try { - $content = $version->content; - $version->version = 0; - $version->content = ''; - $DB->insert_record('wiki_versions', $version); - $version->version = 1; - $version->content = $content; - $DB->insert_record('wiki_versions', $version); - } catch (dml_exception $e) { - debugging($e->getMessage()); - } - } else { - try { - $DB->insert_record('wiki_versions', $version); - } catch (dml_exception $e) { - debugging($e->getMessage()); - } - } - } - - $pagesinfo->close(); -} diff --git a/mod/workshop/db/upgrade.php b/mod/workshop/db/upgrade.php index 3b2dd18fe1e..dd9fb9e514c 100644 --- a/mod/workshop/db/upgrade.php +++ b/mod/workshop/db/upgrade.php @@ -38,286 +38,6 @@ function xmldb_workshop_upgrade($oldversion) { $dbman = $DB->get_manager(); - //===== 1.9.0 upgrade line ======// - - /** - * the following blocks contain all the db/upgrade.php logic from MOODLE_19_STABLE branch - * so that it does not matter if we are upgrading from 1.9.0, 1.9.3 or 1.9.whatever - */ - - if ($oldversion < 2007101510) { - $orphans = $DB->get_records_sql('SELECT wa.id - FROM {workshop_assessments} wa - LEFT JOIN {workshop_submissions} ws ON wa.submissionid = ws.id - WHERE ws.id IS NULL'); - if (!empty($orphans)) { - echo $OUTPUT->notification('Orphaned assessment records found - cleaning...'); - $DB->delete_records_list('workshop_assessments', 'id', array_keys($orphans)); - } - upgrade_mod_savepoint(true, 2007101510, 'workshop'); - } - - //===== end of 1.9.0 upgrade line ======// - - /** - * Upgrading from workshop 1.9.x - big things going to happen now... - * The migration procedure is divided into smaller chunks using incremental - * versions 2009102900, 2009102901, 2009102902 etc. The day zero of the new - * workshop 2.0 is version 2009103000 since when the upgrade code is maintained. - */ - - /** - * Migration from 1.9 - step 1 - rename old tables - */ - if ($oldversion < 2009102901) { - echo $OUTPUT->notification('Renaming old workshop module tables', 'notifysuccess'); - foreach (array('workshop', 'workshop_elements', 'workshop_rubrics', 'workshop_submissions', 'workshop_assessments', - 'workshop_grades', 'workshop_comments', 'workshop_stockcomments') as $tableorig) { - $tablearchive = $tableorig . '_old'; - if ($dbman->table_exists($tableorig)) { - $dbman->rename_table(new xmldb_table($tableorig), $tablearchive); - } - // append a new field 'newplugin' into every archived table. In this field, the name of the subplugin - // who adopted the record during the migration is stored. null value means the record is not migrated yet - $table = new xmldb_table($tablearchive); - $field = new xmldb_field('newplugin', XMLDB_TYPE_CHAR, '28', null, null, null, null); - if (!$dbman->field_exists($table, $field)) { - $dbman->add_field($table, $field); - } - // append a new field 'newid' in every archived table. null value means the record was not migrated yet. - // the field will hold the new id of the migrated record - $table = new xmldb_table($tablearchive); - $field = new xmldb_field('newid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null); - if (!$dbman->field_exists($table, $field)) { - $dbman->add_field($table, $field); - } - } - upgrade_mod_savepoint(true, 2009102901, 'workshop'); - } - - /** - * Migration from 1.9 - step 2 - create new workshop core tables - */ - if ($oldversion < 2009102902) { - require_once(dirname(__FILE__) . '/upgradelib.php'); - echo $OUTPUT->notification('Preparing new workshop module tables', 'notifysuccess'); - workshop_upgrade_prepare_20_tables(); - upgrade_mod_savepoint(true, 2009102902, 'workshop'); - } - - /** - * Migration from 1.9 - step 3 - migrate workshop instances - */ - if ($oldversion < 2009102903) { - require_once(dirname(__FILE__) . '/upgradelib.php'); - echo $OUTPUT->notification('Copying workshop core data', 'notifysuccess'); - workshop_upgrade_module_instances(); - upgrade_mod_savepoint(true, 2009102903, 'workshop'); - } - - /** - * Migration from 1.9 - step 4 - migrate submissions - */ - if ($oldversion < 2009102904) { - require_once(dirname(__FILE__) . '/upgradelib.php'); - echo $OUTPUT->notification('Copying submissions', 'notifysuccess'); - workshop_upgrade_submissions(); - upgrade_mod_savepoint(true, 2009102904, 'workshop'); - } - - /** - * Migration from 1.9 - step 5 - migrate submission attachment to new file storage - */ - if ($oldversion < 2009102905) { - // $filearea = "$workshop->course/$CFG->moddata/workshop/$submission->id"; - $fs = get_file_storage(); - $from = 'FROM {workshop_submissions} s - JOIN {workshop} w ON (w.id = s.workshopid) - JOIN {modules} m ON (m.name = :modulename) - JOIN {course_modules} cm ON (cm.module = m.id AND cm.instance = w.id) - WHERE s.attachment <> 1'; - $params = array('modulename' => 'workshop'); - $count = $DB->count_records_sql('SELECT COUNT(s.id) ' . $from, $params); - $rs = $DB->get_recordset_sql('SELECT s.id, s.authorid, s.workshopid, cm.course, cm.id AS cmid ' . - $from . ' ORDER BY cm.course, w.id', $params); - $pbar = new progress_bar('migrateworkshopsubmissions', 500, true); - $i = 0; - foreach ($rs as $submission) { - $i++; - upgrade_set_timeout(60); // set up timeout, may also abort execution - $pbar->update($i, $count, "Migrating workshop submissions - $i/$count"); - - $filedir = "$CFG->dataroot/$submission->course/$CFG->moddata/workshop/$submission->id"; - if ($files = get_directory_list($filedir, '', false)) { - $context = get_context_instance(CONTEXT_MODULE, $submission->cmid); - foreach ($files as $filename) { - $filepath = $filedir . '/' . $filename; - if (!is_readable($filepath)) { - echo $OUTPUT->notification('File not readable: ' . $filepath); - continue; - } - $filename = clean_param($filename, PARAM_FILE); - if ($filename === '') { - echo $OUTPUT->notification('Unsupported submission filename: ' . $filepath); - continue; - } - if (! $fs->file_exists($context->id, 'mod_workshop', 'submission_attachment', $submission->id, '/', $filename)) { - $filerecord = array('contextid' => $context->id, - 'component' => 'mod_workshop', - 'filearea' => 'submission_attachment', - 'itemid' => $submission->id, - 'filepath' => '/', - 'filename' => $filename, - 'userid' => $submission->authorid); - if ($fs->create_file_from_pathname($filerecord, $filepath)) { - $submission->attachment = 1; - $DB->update_record('workshop_submissions', $submission); - unlink($filepath); - } - } - } - } - // remove dirs if empty - @rmdir("$CFG->dataroot/$submission->course/$CFG->moddata/workshop/$submission->id"); - @rmdir("$CFG->dataroot/$submission->course/$CFG->moddata/workshop"); - @rmdir("$CFG->dataroot/$submission->course/$CFG->moddata"); - @rmdir("$CFG->dataroot/$submission->course"); - } - $rs->close(); - upgrade_mod_savepoint(true, 2009102905, 'workshop'); - } - - /** - * Migration from 1.9 - step 6 - migrate assessments - */ - if ($oldversion < 2009102906) { - require_once(dirname(__FILE__) . '/upgradelib.php'); - echo $OUTPUT->notification('Copying assessments', 'notifysuccess'); - workshop_upgrade_assessments(); - upgrade_mod_savepoint(true, 2009102906, 'workshop'); - } - - /** - * End of migration from 1.9 - */ - - /** - * Add 'published' field into workshop_submissions - */ - if ($oldversion < 2009121800) { - $table = new xmldb_table('workshop_submissions'); - $field = new xmldb_field('published', XMLDB_TYPE_INTEGER, '2', XMLDB_UNSIGNED, null, null, '0', 'timegraded'); - if (!$dbman->field_exists($table, $field)) { - $dbman->add_field($table, $field); - } - upgrade_mod_savepoint(true, 2009121800, 'workshop'); - } - - /** - * Add 'evaluation' field into workshop - */ - if ($oldversion < 2010070700) { - $table = new xmldb_table('workshop'); - $field = new xmldb_field('evaluation', XMLDB_TYPE_CHAR, '30', null, XMLDB_NOTNULL, null, null, 'strategy'); - if (!$dbman->field_exists($table, $field)) { - $dbman->add_field($table, $field); - } - upgrade_mod_savepoint(true, 2010070700, 'workshop'); - } - - /** - * Set the value of the new 'evaluation' field to 'best', there is no alternative at the moment - */ - if ($oldversion < 2010070701) { - $DB->set_field('workshop', 'evaluation', 'best'); - upgrade_mod_savepoint(true, 2010070701, 'workshop'); - } - - /** - * Add 'late' field into workshop_submissions - */ - if ($oldversion < 2010072300) { - $table = new xmldb_table('workshop_submissions'); - $field = new xmldb_field('late', XMLDB_TYPE_INTEGER, '2', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'published'); - if (!$dbman->field_exists($table, $field)) { - $dbman->add_field($table, $field); - } - upgrade_mod_savepoint(true, 2010072300, 'workshop'); - } - - /** - * Create legacy _old tables to sync install.xml and real database - * - * In most cases these tables already exists because they were created during 1.9->2.0 migration - * This step is just for those site that were installed from vanilla 2.0 and these _old tables - * were not created. - * Note that these tables will be dropped again later in 2.x - */ - if ($oldversion < 2010111200) { - foreach (array('workshop', 'workshop_elements', 'workshop_rubrics', 'workshop_submissions', 'workshop_assessments', - 'workshop_grades', 'workshop_comments', 'workshop_stockcomments') as $tableorig) { - $tablearchive = $tableorig . '_old'; - if (!$dbman->table_exists($tablearchive)) { - $dbman->install_one_table_from_xmldb_file($CFG->dirroot.'/mod/workshop/db/install.xml', $tablearchive); - } - } - upgrade_mod_savepoint(true, 2010111200, 'workshop'); - } - - /** - * Check the course_module integrity - see MDL-26312 for details - * - * Because of a bug in Workshop upgrade code, multiple workshop course_modules can - * potentially point to a single workshop instance. The chance is pretty low as in most cases, - * the upgrade failed. But under certain circumstances, workshop could be upgraded with - * this data integrity issue. We want to detect it now and let the admin know. - */ - if ($oldversion < 2011021100) { - $sql = "SELECT cm.id, cm.course, cm.instance - FROM {course_modules} cm - WHERE cm.module IN (SELECT id - FROM {modules} - WHERE name = ?)"; - $rs = $DB->get_recordset_sql($sql, array('workshop')); - $map = array(); // returned stdClasses by instance id - foreach ($rs as $cm) { - $map[$cm->instance][$cm->id] = $cm; - } - $rs->close(); - - $problems = array(); - foreach ($map as $instanceid => $cms) { - if (count($cms) > 1) { - $problems[] = 'workshop instance ' . $instanceid . ' referenced by course_modules ' . implode(', ', array_keys($cms)); - } - } - if ($problems) { - echo $OUTPUT->notification('¡Ay, caramba! Data integrity corruption has been detected in your workshop ' . PHP_EOL . - 'module database tables. This might be caused by a bug in workshop upgrade code. ' . PHP_EOL . - 'Please report this issue immediately in workshop module support forum at ' . PHP_EOL . - 'http://moodle.org so that we can help to fix this problem. Please copy and keep ' . PHP_EOL . - 'following information for future reference:'); - foreach ($problems as $problem) { - echo $OUTPUT->notification($problem); - upgrade_log(UPGRADE_LOG_NOTICE, 'mod_workshop', 'course_modules integrity problem', $problem); - } - } - - unset($problems); - unset($map); - upgrade_mod_savepoint(true, 2011021100, 'workshop'); - } - - // Moodle v2.1.0 release upgrade line - // Put any upgrade step following this - - /** - * Fix the eventually corrupted workshop table id sequence - */ - if ($oldversion < 2011110400) { - $dbman->reset_sequence('workshop'); - upgrade_mod_savepoint(true, 2011110400, 'workshop'); - } // Moodle v2.2.0 release upgrade line // Put any upgrade step following this diff --git a/mod/workshop/db/upgradelib.php b/mod/workshop/db/upgradelib.php deleted file mode 100644 index 14e91ce2ecf..00000000000 --- a/mod/workshop/db/upgradelib.php +++ /dev/null @@ -1,469 +0,0 @@ -. - -/** - * Functions used by some stages in workshop db/upgrade.php - * - * @package mod - * @subpackage workshop - * @copyright 2009 David Mudrak - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ - -/** - * Prepares the inital workshop 2.0 core tables - */ -function workshop_upgrade_prepare_20_tables() { - global $CFG, $DB; - - $dbman = $DB->get_manager(); - - if (!$dbman->table_exists('workshop')) { - $table = new xmldb_table('workshop'); - $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); - $table->add_field('course', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null); - $table->add_field('name', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null); - $table->add_field('intro', XMLDB_TYPE_TEXT, 'big', null, null, null, null); - $table->add_field('introformat', XMLDB_TYPE_INTEGER, '3', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); - $table->add_field('instructauthors', XMLDB_TYPE_TEXT, 'big', null, null, null, null); - $table->add_field('instructauthorsformat', XMLDB_TYPE_INTEGER, '3', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); - $table->add_field('instructreviewers', XMLDB_TYPE_TEXT, 'big', null, null, null, null); - $table->add_field('instructreviewersformat', XMLDB_TYPE_INTEGER, '3', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); - $table->add_field('timemodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null); - $table->add_field('phase', XMLDB_TYPE_INTEGER, '3', XMLDB_UNSIGNED, null, null, '0'); - $table->add_field('useexamples', XMLDB_TYPE_INTEGER, '2', XMLDB_UNSIGNED, null, null, '0'); - $table->add_field('usepeerassessment', XMLDB_TYPE_INTEGER, '2', XMLDB_UNSIGNED, null, null, '0'); - $table->add_field('useselfassessment', XMLDB_TYPE_INTEGER, '2', XMLDB_UNSIGNED, null, null, '0'); - $table->add_field('grade', XMLDB_TYPE_NUMBER, '10, 5', XMLDB_UNSIGNED, null, null, '80'); - $table->add_field('gradinggrade', XMLDB_TYPE_NUMBER, '10, 5', XMLDB_UNSIGNED, null, null, '20'); - $table->add_field('strategy', XMLDB_TYPE_CHAR, '30', null, XMLDB_NOTNULL, null, null); - $table->add_field('gradedecimals', XMLDB_TYPE_INTEGER, '3', XMLDB_UNSIGNED, null, null, '0'); - $table->add_field('nattachments', XMLDB_TYPE_INTEGER, '3', XMLDB_UNSIGNED, null, null, '0'); - $table->add_field('latesubmissions', XMLDB_TYPE_INTEGER, '2', XMLDB_UNSIGNED, null, null, '0'); - $table->add_field('maxbytes', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, '100000'); - $table->add_field('examplesmode', XMLDB_TYPE_INTEGER, '3', XMLDB_UNSIGNED, null, null, '0'); - $table->add_field('submissionstart', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, '0'); - $table->add_field('submissionend', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, '0'); - $table->add_field('assessmentstart', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, '0'); - $table->add_field('assessmentend', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, '0'); - $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); - $table->add_key('course_fk', XMLDB_KEY_FOREIGN, array('course'), 'course', array('id')); - $dbman->create_table($table); - } - - if (!$dbman->table_exists('workshop_submissions')) { - $table = new xmldb_table('workshop_submissions'); - $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); - $table->add_field('workshopid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null); - $table->add_field('example', XMLDB_TYPE_INTEGER, '2', XMLDB_UNSIGNED, null, null, '0'); - $table->add_field('authorid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null); - $table->add_field('timecreated', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null); - $table->add_field('timemodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null); - $table->add_field('title', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null); - $table->add_field('content', XMLDB_TYPE_TEXT, 'big', null, null, null, null); - $table->add_field('contentformat', XMLDB_TYPE_INTEGER, '3', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); - $table->add_field('contenttrust', XMLDB_TYPE_INTEGER, '3', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); - $table->add_field('attachment', XMLDB_TYPE_INTEGER, '2', XMLDB_UNSIGNED, null, null, '0'); - $table->add_field('grade', XMLDB_TYPE_NUMBER, '10, 5', XMLDB_UNSIGNED, null, null, null); - $table->add_field('gradeover', XMLDB_TYPE_NUMBER, '10, 5', XMLDB_UNSIGNED, null, null, null); - $table->add_field('gradeoverby', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null); - $table->add_field('feedbackauthor', XMLDB_TYPE_TEXT, 'big', null, null, null, null); - $table->add_field('feedbackauthorformat', XMLDB_TYPE_INTEGER, '3', XMLDB_UNSIGNED, null, null, '0'); - $table->add_field('timegraded', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null); - $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); - $table->add_key('workshop_fk', XMLDB_KEY_FOREIGN, array('workshopid'), 'workshop', array('id')); - $table->add_key('overriddenby_fk', XMLDB_KEY_FOREIGN, array('gradeoverby'), 'user', array('id')); - $table->add_key('author_fk', XMLDB_KEY_FOREIGN, array('authorid'), 'user', array('id')); - $dbman->create_table($table); - } - - if (!$dbman->table_exists('workshop_assessments')) { - $table = new xmldb_table('workshop_assessments'); - $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); - $table->add_field('submissionid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null); - $table->add_field('reviewerid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null); - $table->add_field('weight', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '1'); - $table->add_field('timecreated', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, '0'); - $table->add_field('timemodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, '0'); - $table->add_field('grade', XMLDB_TYPE_NUMBER, '10, 5', XMLDB_UNSIGNED, null, null, null); - $table->add_field('gradinggrade', XMLDB_TYPE_NUMBER, '10, 5', XMLDB_UNSIGNED, null, null, null); - $table->add_field('gradinggradeover', XMLDB_TYPE_NUMBER, '10, 5', XMLDB_UNSIGNED, null, null, null); - $table->add_field('gradinggradeoverby', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null); - $table->add_field('feedbackauthor', XMLDB_TYPE_TEXT, 'big', null, null, null, null); - $table->add_field('feedbackauthorformat', XMLDB_TYPE_INTEGER, '3', XMLDB_UNSIGNED, null, null, '0'); - $table->add_field('feedbackreviewer', XMLDB_TYPE_TEXT, 'big', null, null, null, null); - $table->add_field('feedbackreviewerformat', XMLDB_TYPE_INTEGER, '3', XMLDB_UNSIGNED, null, null, '0'); - $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); - $table->add_key('submission_fk', XMLDB_KEY_FOREIGN, array('submissionid'), 'workshop_submissions', array('id')); - $table->add_key('overriddenby_fk', XMLDB_KEY_FOREIGN, array('gradinggradeoverby'), 'user', array('id')); - $table->add_key('reviewer_fk', XMLDB_KEY_FOREIGN, array('reviewerid'), 'user', array('id')); - $dbman->create_table($table); - } - - if (!$dbman->table_exists('workshop_grades')) { - $table = new xmldb_table('workshop_grades'); - $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); - $table->add_field('assessmentid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null); - $table->add_field('strategy', XMLDB_TYPE_CHAR, '30', null, XMLDB_NOTNULL, null, null); - $table->add_field('dimensionid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null); - $table->add_field('grade', XMLDB_TYPE_NUMBER, '10, 5', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null); - $table->add_field('peercomment', XMLDB_TYPE_TEXT, 'big', null, null, null, null); - $table->add_field('peercommentformat', XMLDB_TYPE_INTEGER, '3', null, null, null, '0'); - $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); - $table->add_key('assessment_fk', XMLDB_KEY_FOREIGN, array('assessmentid'), 'workshop_assessments', array('id')); - $table->add_key('formfield_uk', XMLDB_KEY_UNIQUE, array('assessmentid', 'strategy', 'dimensionid')); - $dbman->create_table($table); - } - - if (!$dbman->table_exists('workshop_aggregations')) { - $table = new xmldb_table('workshop_aggregations'); - $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); - $table->add_field('workshopid', 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('gradinggrade', XMLDB_TYPE_NUMBER, '10, 5', XMLDB_UNSIGNED, null, null, null); - $table->add_field('timegraded', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null); - $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); - $table->add_key('workshop_fk', XMLDB_KEY_FOREIGN, array('workshopid'), 'workshop', array('id')); - $table->add_key('user_fk', XMLDB_KEY_FOREIGN, array('userid'), 'user', array('id')); - $table->add_key('workshopuser', XMLDB_KEY_UNIQUE, array('workshopid', 'userid')); - $dbman->create_table($table); - } -} - -/** - * Copies the records from workshop_old into workshop table - * - * @return void - */ -function workshop_upgrade_module_instances() { - global $CFG, $DB; - - upgrade_set_timeout(); - $moduleid = $DB->get_field('modules', 'id', array('name' => 'workshop'), MUST_EXIST); - $rs = $DB->get_recordset_select('workshop_old', 'newid IS NULL', null, 'id'); - foreach ($rs as $old) { - $new = workshop_upgrade_transform_instance($old); - $new->id = $old->id; - $DB->import_record('workshop', $new); - $DB->set_field('workshop_old', 'newplugin', 'workshop', array('id' => $old->id)); - $DB->set_field('workshop_old', 'newid', $new->id, array('id' => $old->id)); - } - $rs->close(); - $dbman = $DB->get_manager(); - $dbman->reset_sequence('workshop'); -} - -/** - * Given a record containing data from 1.9 workshop table, returns object containing data as should be saved in 2.0 workshop table - * - * @param stdClass $old record from 1.9 workshop table - * @return stdClass - */ -function workshop_upgrade_transform_instance(stdClass $old) { - global $CFG; - require_once(dirname(dirname(__FILE__)) . '/locallib.php'); - - $new = new stdClass(); - $new->course = $old->course; - $new->name = $old->name; - $new->intro = $old->description; - $new->introformat = $old->format; - $new->nattachments = $old->nattachments; - $new->maxbytes = $old->maxbytes; - $new->grade = $old->grade; - $new->gradinggrade = $old->gradinggrade; - $new->phase = workshop::PHASE_CLOSED; - $new->timemodified = time(); - if ($old->ntassessments > 0) { - $new->useexamples = 1; - } else { - $new->useexamples = 0; - } - $new->usepeerassessment = 1; - $new->useselfassessment = $old->includeself; - switch ($old->gradingstrategy) { - case 0: // 'notgraded' - renamed - $new->strategy = 'comments'; - break; - case 1: // 'accumulative' - $new->strategy = 'accumulative'; - break; - case 2: // 'errorbanded' - renamed - $new->strategy = 'numerrors'; - break; - case 3: // 'criterion' - will be migrated into 'rubric' - $new->strategy = 'rubric'; - break; - case 4: // 'rubric' - $new->strategy = 'rubric'; - break; - } - if ($old->submissionstart < $old->submissionend) { - $new->submissionstart = $old->submissionstart; - $new->submissionend = $old->submissionend; - } - if ($old->assessmentstart < $old->assessmentend) { - $new->assessmentstart = $old->assessmentstart; - $new->assessmentend = $old->assessmentend; - } - - return $new; -} - -/** - * Copies records from workshop_submissions_old into workshop_submissions. Can be called after all workshop module instances - * were correctly migrated and new ids are filled in workshop_old - * - * @return void - */ -function workshop_upgrade_submissions() { - global $CFG, $DB; - - upgrade_set_timeout(); - - // list of teachers in every workshop: array of (int)workshopid => array of (int)userid => notused - $workshopteachers = array(); - - $rs = $DB->get_recordset_select('workshop_submissions_old', 'newid IS NULL'); - foreach ($rs as $old) { - if (!isset($workshopteachers[$old->workshopid])) { - $cm = get_coursemodule_from_instance('workshop', $old->workshopid, 0, false, MUST_EXIST); - $context = get_context_instance(CONTEXT_MODULE, $cm->id); - $workshopteachers[$old->workshopid] = get_users_by_capability($context, 'mod/workshop:manage', 'u.id'); - } - $new = workshop_upgrade_transform_submission($old, $old->workshopid, $workshopteachers[$old->workshopid]); - $newid = $DB->insert_record('workshop_submissions', $new, true, true); - $DB->set_field('workshop_submissions_old', 'newplugin', 'submissions', array('id' => $old->id)); - $DB->set_field('workshop_submissions_old', 'newid', $newid, array('id' => $old->id)); - } - $rs->close(); -} - -/** - * Given a record from 1.x workshop_submissions_old, returns data for 2.0 workshop_submissions - * - * @param stdClass $old - * @param int $newworkshopid new workshop id - * @param array $legacyteachers $userid => notused the list of legacy workshop teachers for the submission's workshop - * @return stdClass - */ -function workshop_upgrade_transform_submission(stdClass $old, $newworkshopid, array $legacyteachers) { - - $new = new stdclass(); // new submission record to be returned - $new->workshopid = $newworkshopid; - - if (isset($legacyteachers[$old->userid])) { - // the author of the submission was teacher = had mod/workshop:manage. this is the only way how we can - // recognize the submission should be treated as example submission (ach jo...) - $new->example = 1; - } else { - $new->example = 0; - } - - $new->authorid = $old->userid; - $new->timecreated = $old->timecreated; - $new->timemodified = $old->timecreated; - $new->title = $old->title; - $new->content = $old->description; - $new->contentformat = FORMAT_HTML; - $new->contenttrust = 0; - $new->published = 0; - - return $new; -} - -/** - * Returns the list of new submission instances ids - * - * @return array (int)oldid => (int)newid - */ -function workshop_upgrade_submission_id_mappings() { - global $DB; - - $oldrecords = $DB->get_records('workshop_submissions_old', null, 'id', 'id,newid'); - $newids = array(); - foreach ($oldrecords as $oldid => $oldrecord) { - if ($oldrecord->id and $oldrecord->newid) { - $newids[$oldid] = $oldrecord->newid; - } - } - return $newids; -} - -/** - * Returns the list of teacherweight values as were set in legacy workshop instances - * - * @return array (int)oldid => (int)teacherweight - */ -function workshop_upgrade_legacy_teacher_weights() { - global $DB; - - $oldrecords = $DB->get_records('workshop_old', null, 'id', 'id,teacherweight'); - $weights = array(); - foreach ($oldrecords as $oldid => $oldrecord) { - if (is_null($oldrecord->teacherweight)) { - $weights[$oldid] = 1; - } else { - $weights[$oldid] = $oldrecord->teacherweight; - } - } - return $weights; -} - -/** - * Copies all assessments from workshop_assessments_old to workshop_assessments. Can be called after all - * submissions were migrated. - * - * @return void - */ -function workshop_upgrade_assessments() { - global $CFG, $DB, $OUTPUT; - - upgrade_set_timeout(); - - $newsubmissionids = workshop_upgrade_submission_id_mappings(); - $teacherweights = workshop_upgrade_legacy_teacher_weights(); - - // list of teachers in every workshop: array of (int)workshopid => array of (int)userid => notused - $workshopteachers = array(); - - // get the list of ids of the new example submissions - $examplesubmissions = $DB->get_records('workshop_submissions', array('example' => 1), '', 'id'); - - $rs = $DB->get_recordset_select('workshop_assessments_old', 'newid IS NULL'); - foreach ($rs as $old) { - if (!isset($workshopteachers[$old->workshopid])) { - $cm = get_coursemodule_from_instance('workshop', $old->workshopid, 0, false, MUST_EXIST); - $context = get_context_instance(CONTEXT_MODULE, $cm->id); - $workshopteachers[$old->workshopid] = get_users_by_capability($context, 'mod/workshop:manage', 'u.id'); - } - $ofexample = isset($examplesubmissions[$newsubmissionids[$old->submissionid]]); - $new = workshop_upgrade_transform_assessment($old, $newsubmissionids[$old->submissionid], - $workshopteachers[$old->workshopid], $teacherweights[$old->workshopid], $ofexample); - $newid = $DB->insert_record('workshop_assessments', $new, true, true); - $DB->set_field('workshop_assessments_old', 'newplugin', 'assessments', array('id' => $old->id)); - $DB->set_field('workshop_assessments_old', 'newid', $newid, array('id' => $old->id)); - } - $rs->close(); -} - -/** - * Given a record from workshop_assessments_old, returns record to be stored in workshop_assessment - * - * @param stdClass $old record from workshop_assessments_old, - * @param int $newsubmissionid new submission id - * @param array $legacyteachers (int)userid => notused the list of legacy workshop teachers for the submission's workshop - * @param int $legacyteacherweight weight of teacher's assessment in legacy workshop - * @param bool $ofexample is this the assessment of an example submission? - * @return stdClass - */ -function workshop_upgrade_transform_assessment(stdClass $old, $newsubmissionid, array $legacyteachers, $legacyteacherweight, $ofexample) { - global $CFG; - require_once($CFG->libdir . '/gradelib.php'); - - $new = new stdclass(); - $new->submissionid = $newsubmissionid; - $new->reviewerid = $old->userid; - - if ($ofexample) { - // this is the assessment of an example submission - if (isset($legacyteachers[$old->userid])) { - // this is probably the reference assessment of the example submission - $new->weight = 1; - } else { - $new->weight = 0; - } - - } else { - if (isset($legacyteachers[$old->userid])) { - $new->weight = $legacyteacherweight; - } else { - $new->weight = 1; - } - } - - if ($old->grade < 0) { - // in workshop 1.x, this is just allocated assessment that has not been touched yet, having timecreated one year in the future :-/ - $new->timecreated = time(); - } else { - $new->grade = grade_floatval($old->grade); - if ($old->teachergraded) { - $new->gradinggradeover = grade_floatval($old->gradinggrade); - } else { - $new->gradinggrade = grade_floatval($old->gradinggrade); - } - $new->feedbackauthor = $old->generalcomment; - $new->feedbackauthorformat = FORMAT_HTML; - $new->feedbackreviewer = $old->teachercomment; - $new->feedbackreviewerformat = FORMAT_HTML; - $new->timecreated = $old->timecreated; - $new->timemodified = $old->timegraded; - } - - return $new; -} - -/** - * Returns the list of new assessment ids - * - * @return array (int)oldid => (int)newid - */ -function workshop_upgrade_assessment_id_mappings() { - global $DB; - - $oldrecords = $DB->get_records('workshop_assessments_old', null, 'id', 'id,newid'); - $newids = array(); - foreach ($oldrecords as $oldid => $oldrecord) { - if ($oldrecord->id and $oldrecord->newid) { - $newids[$oldid] = $oldrecord->newid; - } - } - return $newids; -} - -/** - * Returns the list of new element (dimension) ids - * - * @param string $strategy the name of strategy subplugin that the element was migrated into - * @return array (int)workshopid => array (int)elementno => stdclass ->(int)newid {->(string)type} {->(int)maxscore} - */ -function workshop_upgrade_element_id_mappings($strategy) { - global $DB; - - $oldrecords = $DB->get_records('workshop_elements_old', array('newplugin' => $strategy), - 'workshopid,elementno', 'id,workshopid,elementno,scale,maxscore,newid'); - $newids = array(); - foreach ($oldrecords as $old) { - if (!isset($newids[$old->workshopid])) { - $newids[$old->workshopid] = array(); - } - $info = new stdclass(); - $info->newid = $old->newid; - if ($strategy == 'accumulative') { - if ($old->scale >= 0 and $old->scale <= 6) { - $info->type = 'scale'; - } else { - $info->type = 'value'; - } - } - if ($strategy == 'rubric_levels') { - $info->maxscore = $old->maxscore; - } - $newids[$old->workshopid][$old->elementno] = $info; - } - return $newids; -}