From cff86c5c6d469ddfed26b5bbe1e105f8f07c358f Mon Sep 17 00:00:00 2001
From: Jan-Hendrik Willms <tleilax+studip@gmail.com>
Date: Fri, 15 Oct 2021 09:26:47 +0000
Subject: [PATCH] align open groups config for my courses and notifications,
 fixes #328

---
 app/controllers/settings/notification.php     |  8 +++--
 .../5.1.4_fix_my_courses_group_config.php     | 29 +++++++++++++++++++
 2 files changed, 34 insertions(+), 3 deletions(-)
 create mode 100644 db/migrations/5.1.4_fix_my_courses_group_config.php

diff --git a/app/controllers/settings/notification.php b/app/controllers/settings/notification.php
index 1c2b19821d0..12245f3d9fa 100644
--- a/app/controllers/settings/notification.php
+++ b/app/controllers/settings/notification.php
@@ -180,8 +180,10 @@ class Settings_NotificationController extends Settings_SettingsController
      */
     public function open_action($id)
     {
-        $open      = $this->config->MY_COURSES_OPEN_GROUPS;
-        $open[$id] = true;
+        $open = $this->config->MY_COURSES_OPEN_GROUPS;
+        if (!in_array($id, $open)) {
+            $open[] = $id;
+        }
         $this->config->store('MY_COURSES_OPEN_GROUPS', $open);
 
         $this->redirect('settings/notification');
@@ -195,7 +197,7 @@ class Settings_NotificationController extends Settings_SettingsController
     public function close_action($id)
     {
         $open = $this->config->MY_COURSES_OPEN_GROUPS;
-        unset($open[$id]);
+        $open = array_diff($open, [$id]);
         $this->config->store('MY_COURSES_OPEN_GROUPS', $open);
 
         $this->redirect('settings/notification');
diff --git a/db/migrations/5.1.4_fix_my_courses_group_config.php b/db/migrations/5.1.4_fix_my_courses_group_config.php
new file mode 100644
index 00000000000..427bcd2a8ca
--- /dev/null
+++ b/db/migrations/5.1.4_fix_my_courses_group_config.php
@@ -0,0 +1,29 @@
+<?php
+final class FixMyCoursesGroupConfig extends Migration
+{
+    public function up()
+    {
+        ConfigValue::findEachBySQL(
+            function ($value) {
+                $groups = json_decode($value->value, true);
+
+                $changed = false;
+                foreach ($groups as $index => $val) {
+                    if ($val === true) {
+                        unset($groups[$index]);
+                        $groups[] = $index;
+
+                        $changed = true;
+                    }
+                }
+
+                if ($changed) {
+                    $value->value = json_encode($groups);
+                    $value->store();
+                }
+            },
+            'field = ?',
+            ['MY_COURSES_OPEN_GROUPS']
+        );
+    }
+}
-- 
GitLab