From 9eebd58aa2749d8019e387e6df540df1dbda9be7 Mon Sep 17 00:00:00 2001
From: Michael Hawkins <michaelh@moodle.com>
Date: Fri, 27 Sep 2019 18:10:30 +0800
Subject: [PATCH] MDL-66695 forumreport_summary: Added handling for all groups
 view count

Part of MDL-66076.
---
 .../report/summary/classes/summary_table.php  | 30 +++++++++++++++----
 1 file changed, 24 insertions(+), 6 deletions(-)

diff --git a/mod/forum/report/summary/classes/summary_table.php b/mod/forum/report/summary/classes/summary_table.php
index e9c5e07bd40..eeec8d5c53e 100644
--- a/mod/forum/report/summary/classes/summary_table.php
+++ b/mod/forum/report/summary/classes/summary_table.php
@@ -115,7 +115,7 @@ class summary_table extends table_sql {
         ];
 
         // Only include viewcount column when no groups filter is applied.
-        if (empty($filters['groups'])) {
+        if (!$this->is_filtered_by_groups($filters['groups'])) {
             $this->logreader = $this->get_internal_log_reader();
             if ($this->logreader) {
                 $columnheaders['viewcount'] = get_string('viewcount', 'forumreport_summary');
@@ -288,12 +288,8 @@ class summary_table extends table_sql {
                 break;
 
             case self::FILTER_GROUPS:
-                // Find total number of options available (groups plus 'no groups').
-                $availablegroups = groups_get_activity_allowed_groups($this->cm);
-                $alloptionscount = 1 + count($availablegroups);
-
                 // Skip adding filter if not applied, or all options are selected.
-                if (!empty($values) && count($values) < $alloptionscount) {
+                if ($this->is_filtered_by_groups($values)) {
                     // Include users without groups if that option (-1) is selected.
                     $nonekey = array_search(-1, $values, true);
 
@@ -614,4 +610,26 @@ class summary_table extends table_sql {
 
         $dbman->create_temp_table($xmldbtable);
     }
+
+    /**
+     * Check whether the groups filter will be applied by checking whether the number of groups selected
+     * matches the total number of options available (all groups plus no groups option).
+     *
+     * @param array $groups The group IDs selected.
+     * @return bool
+     */
+    protected function is_filtered_by_groups(array $groups): bool {
+        static $groupsavailablecount = null;
+
+        if (empty($groups)) {
+            return false;
+        }
+
+        // Find total number of options available (groups plus 'no groups'), if not already fetched.
+        if (is_null($groupsavailablecount)) {
+            $groupsavailablecount = 1 + count(groups_get_activity_allowed_groups($this->cm));
+        }
+
+        return (count($groups) < $groupsavailablecount);
+    }
 }