From c75ba879bb4d855cba8bd14abfdf7cdb93927ba5 Mon Sep 17 00:00:00 2001
From: sam_marshall <sam_marshall>
Date: Tue, 27 May 2008 10:16:25 +0000
Subject: [PATCH] MDL-15015: Choice limited answers don't work with group mode

---
 mod/choice/lib.php | 45 ++++++++++++++++++++++++++++++++++-----------
 1 file changed, 34 insertions(+), 11 deletions(-)

diff --git a/mod/choice/lib.php b/mod/choice/lib.php
index cf767aab8a..2c500d3960 100644
--- a/mod/choice/lib.php
+++ b/mod/choice/lib.php
@@ -242,20 +242,43 @@ function choice_user_submit_response($formanswer, $choice, $userid, $courseid, $
 
     $current = get_record('choice_answers', 'choiceid', $choice->id, 'userid', $userid);
     $context = get_context_instance(CONTEXT_MODULE, $cm->id);
-    $countanswers = get_records("choice_answers", "optionid", $formanswer);
-    if ($countanswers) {
-        $countans = 0;
-        foreach ($countanswers as $ca) { //only return enrolled users.
-            if (has_capability('mod/choice:choose', $context, $ca->userid, false)) {
-                $countans = $countans+1;
-            }
+
+    $countanswers=0;
+    if($choice->limitanswers) {
+        // Find out whether groups are being used and enabled
+        if (groups_get_activity_groupmode($cm) > 0) {
+            $currentgroup = groups_get_activity_group($cm);
+        } else {
+            $currentgroup = 0;
+        }
+        if($currentgroup) {
+            // If groups are being used, retrieve responses only for users in
+            // current group
+            global $CFG;
+            $answers = get_records_sql("
+SELECT 
+    ca.*
+FROM 
+    {$CFG->prefix}choice_answers ca
+    INNER JOIN {$CFG->prefix}groups_members gm ON ca.userid=gm.userid
+WHERE
+    optionid=$formanswer
+    AND gm.groupid=$currentgroup");
+        } else {
+            // Groups are not used, retrieve all answers for this option ID
+            $answers = get_records("choice_answers", "optionid", $formanswer);
         }
 
-        $countanswers = $countans;
-    } else {
-        $countanswers = 0;
+        $countanswers=0;
+        if ($answers) {
+            foreach ($answers as $a) { //only return enrolled users.
+                if (has_capability('mod/choice:choose', $context, $a->userid, false)) {
+                    $countanswers++;
+                }
+            }
+        }
+        $maxans = $choice->maxanswers[$formanswer];
     }
-    $maxans = $choice->maxanswers[$formanswer];
 
     if (!($choice->limitanswers && ($countanswers >= $maxans) )) {
         if ($current) {
-- 
2.39.5