--- similar.module-orig	2007-11-20 06:26:30.000000000 +0100
+++ similar.module	2008-05-23 01:45:34.792414250 +0200
@@ -360,6 +360,8 @@
     list(,$types) = each($types);
   }
   $types = "'$types'";
+
+  $join_taxonomy = '';
   if (module_exists('taxonomy') && (variable_get('similar_taxonomy_filter', 0) == 2 && $taxonomy_tids = variable_get('similar_taxonomy_tids', array()))
                                  || (variable_get('similar_taxonomy_filter', 0) == 1 && $taxonomy_tids = _similar_taxonomy_membership($node->nid))) {
     array_walk($taxonomy_tids, '_similar_force_int');
@@ -370,11 +372,21 @@
       list(,$taxonomy_tids) = each($taxonomy_tids);
       $taxonomy_tids = (int)$taxonomy_tids;
     }
+    $join_taxonomy = "INNER JOIN {term_node} t ON n.nid = t.nid AND t.tid IN ($taxonomy_tids)";
+  };
+
+  $join_og ='';		$where_og = '';
+  if (module_exists('og')) {
+     global $user;
 
-    $result = db_query_range("SELECT r.nid, MATCH(r.body, r.title) AGAINST ('%s') AS score FROM {node_revisions} r INNER JOIN {node} n ON r.nid = n.nid AND r.vid = n.vid INNER JOIN {term_node} t ON n.nid = t.nid AND t.tid IN ($taxonomy_tids) WHERE MATCH(r.body, r.title) AGAINST ('%s') AND n.status <> 0 AND r.nid <> %d AND n.type IN ($types) GROUP BY n.nid ORDER BY score DESC, r.vid DESC", $text, $text, $node->nid, 0, variable_get('similar_num_display', 5));
-  } else {
-    $result = db_query_range("SELECT r.nid, MATCH(r.body, r.title) AGAINST ('%s') AS score FROM {node_revisions} r INNER JOIN {node} n ON r.nid = n.nid AND r.vid = n.vid WHERE MATCH(r.body, r.title) AGAINST ('%s') AND n.status <> 0 AND r.nid <> %d AND n.type IN ($types) GROUP BY n.nid ORDER BY score DESC, r.vid DESC", $text, $text, $node->nid, 0, variable_get('similar_num_display', 5));
+	# get groups and users belonging to these groups
+    $join_og = 'LEFT OUTER JOIN {og_ancestry} AS a on n.nid = a.nid LEFT OUTER JOIN {og_uid} AS u on a.group_nid = u.nid ';
+	# user is member of group OR node is public (does not belong to any group)
+    $where_og = " (u.uid = $user->uid OR a.nid is null) AND ";
   }
+
+  $result = db_query_range("SELECT DISTINCT r.nid, MATCH(r.body, r.title) AGAINST ('%s') AS score FROM {node_revisions} r INNER JOIN {node} n ON r.nid = n.nid AND r.vid = n.vid $join_taxonomy $join_og WHERE $where_og MATCH(r.body, r.title) AGAINST ('%s') AND n.status <> 0 AND r.nid <> %d AND n.type IN ($types) GROUP BY n.nid ORDER BY score DESC, r.vid DESC", $text, $text, $node->nid, 0, variable_get('similar_num_display', 5));
+
   while ($node = db_fetch_object($result)) {
     $content = node_load($node->nid);
     if ($teaser) {
