From 923ed011916302d63c9279dd0c5fd050478e3406 Mon Sep 17 00:00:00 2001
From: Andrew Berry <deviantintegral@gmail.com>
Date: Mon, 2 Jul 2012 17:07:46 -0400
Subject: [PATCH] Issue #1668740: Only query forum counts for nodes that are
 associated with the forum vocabulary.

---
 includes/core-overrides.inc | 35 +++++++++++++++++++++++++++++++++++
 1 file changed, 35 insertions(+)

diff --git a/includes/core-overrides.inc b/includes/core-overrides.inc
index 89bdf36..01336e0 100644
--- a/includes/core-overrides.inc
+++ b/includes/core-overrides.inc
@@ -152,6 +152,30 @@ function advanced_forum_forum_load($tid = NULL) {
     $query->join('forum', 'f', 'n.vid = f.vid');
     $query->addExpression('COUNT(n.nid)', 'topic_count');
     $query->addExpression('SUM(ncs.comment_count)', 'comment_count');
+
+    // Limit the query to only node types that can actually be associated with
+    // the forum vocabulary.
+    if ($vid) {
+      $vocabulary = taxonomy_vocabulary_load($vid);
+      $vocabulary_fields = field_read_fields(array('module' => 'taxonomy'));
+      $node_types = array();
+      foreach ($vocabulary_fields as $field_name => $vocabulary_field) {
+        foreach ($vocabulary_field['settings']['allowed_values'] as $key => $allowed_value) {
+          if ($allowed_value['vocabulary'] = $vocabulary->machine_name) {
+            $field_info = field_info_field($field_name);
+            if (isset($field_info['bundles']['node'])) {
+              $node_types += $field_info['bundles']['node'];
+            }
+          }
+        }
+      }
+
+      if (!empty($node_types)) {
+        array_walk($node_types, '_advanced_forum_quote_string_array');
+        $query->condition('type', $node_types, 'IN');
+      }
+    }
+
     $counts = $query
         ->fields('f', array('tid'))
         ->condition('status', 1)
@@ -237,3 +261,14 @@ function advanced_forum_get_topics($tid, $sortby, $forum_per_page, $sort_form =
   return $view->preview('default', array($tid));
 }
 
+/**
+ * array_walk() callback to add double-quotes around an array of strings, in
+ * preparation for an implode() call.
+ *
+ * @param &$string
+ *   The string to wrap in double-quotes.
+ */
+function _advanced_forum_quote_string_array(&$string) {
+  $string = '"' . $string . '"';
+}
+
-- 
1.7.11.1

