From 05f9380cbc8eb9e856d8e4bc7bb70eac2a92d416 Mon Sep 17 00:00:00 2001 From: Tobias Reischmann Date: Thu, 17 Aug 2017 17:01:22 +0200 Subject: [PATCH] MDL-59854 forum: Created unique db key for forum_subscriptions Due to race conditions in the function subscribe_user it was possible to create duplicate forum subscriptions. This lead to error messages, when displaying the list of all subscriptions. This patch removes all existing duplicate entries and creates a unique db key to prevent this from happening in the future. --- mod/forum/db/install.xml | 3 ++- mod/forum/db/upgrade.php | 30 ++++++++++++++++++++++++++++++ mod/forum/version.php | 2 +- 3 files changed, 33 insertions(+), 2 deletions(-) mode change 100644 => 100755 mod/forum/db/install.xml diff --git a/mod/forum/db/install.xml b/mod/forum/db/install.xml old mode 100644 new mode 100755 index e1c33097e0d..cbd19068a57 --- a/mod/forum/db/install.xml +++ b/mod/forum/db/install.xml @@ -1,5 +1,5 @@ - @@ -118,6 +118,7 @@ + diff --git a/mod/forum/db/upgrade.php b/mod/forum/db/upgrade.php index 0ab1e6d8a39..7d398bbc839 100644 --- a/mod/forum/db/upgrade.php +++ b/mod/forum/db/upgrade.php @@ -84,5 +84,35 @@ function xmldb_forum_upgrade($oldversion) { // Automatically generated Moodle v3.3.0 release upgrade line. // Put any upgrade step following this. + if ($oldversion < 2017092200) { + + // Remove duplicate entries from forum_subscriptions. + // Find records with multiple userid/forum combinations and find the highest ID. + // Later we will remove all those entries. + $sql = " + SELECT MIN(id) as minid, userid, forum + FROM {forum_subscriptions} + GROUP BY userid, forum + HAVING COUNT(id) > 1"; + + if ($duplicatedrows = $DB->get_recordset_sql($sql)) { + foreach ($duplicatedrows as $row) { + $DB->delete_records_select('forum_subscriptions', + 'userid = :userid AND forum = :forum AND id <> :minid', (array)$row); + } + } + $duplicatedrows->close(); + + // Define key useridforum (primary) to be added to forum_subscriptions. + $table = new xmldb_table('forum_subscriptions'); + $key = new xmldb_key('useridforum', XMLDB_KEY_UNIQUE, array('userid', 'forum')); + + // Launch add key useridforum. + $dbman->add_key($table, $key); + + // Forum savepoint reached. + upgrade_mod_savepoint(true, 2017092200, 'forum'); + } + return true; } diff --git a/mod/forum/version.php b/mod/forum/version.php index 4cf8d418d69..3d140a92e9a 100644 --- a/mod/forum/version.php +++ b/mod/forum/version.php @@ -24,6 +24,6 @@ defined('MOODLE_INTERNAL') || die(); -$plugin->version = 2017051500; // The current module version (Date: YYYYMMDDXX) +$plugin->version = 2017092200; // The current module version (Date: YYYYMMDDXX) $plugin->requires = 2017050500; // Requires this Moodle version $plugin->component = 'mod_forum'; // Full name of the plugin (used for diagnostics)