--- tac_lite.module.orig	2009-06-14 00:58:27.000000000 -0700
+++ tac_lite.module	2009-06-14 01:20:00.000000000 -0700
@@ -464,6 +466,11 @@
 function tac_lite_db_rewrite_sql($query, $primary_table, $primary_field, $args) {
   global $user;
   
+  if ($primary_field != 'tid') {
+    // Only changes things in link with 'tid'
+    return;
+  }
+  
   if (user_access('administer tac_lite')) {
     // Only for tac_lite administrators.
     return;
@@ -471,10 +478,14 @@
   
   // the vocabularies containing protected info.
   $vids = variable_get('tac_lite_categories', array(0));
+  if (!is_array($vids) || !count($vids)) {
+    return;
+  }
   
   // the terms this user is allowed to see
   $tids = array();
-  for ($i = 1; $i <= variable_get('tac_lite_schemes', 1); $i++) {
+  $max = variable_get('tac_lite_schemes', 1);
+  for ($i = 1; $i <= $max; $i++) {
     $config = _tac_lite_config($i);
     if (in_array('grant_view', $config['perms'])) {
       $tids = array_merge($tids, _tac_lite_user_tids($user, $i));
@@ -484,18 +495,12 @@
   // Note that if tac_lite is configured, but no schemes support grant_view,
   // we assume everyone can view all terms.
 
-  if (count($tids) && is_array($vids) && count($vids)) {
-    switch ($primary_field) {
-    case 'tid':
-      // prevent users from seeing terms they do not have permission to read.
-      $join = "LEFT JOIN {term_data} tac_td ON $primary_table.tid = tac_td.tid";
-      $where = "$primary_table.tid IN (". implode(', ', $tids) .") OR tac_td.vid NOT IN (". implode(',', $vids) .")"; 
-      
-      return array('join' => $join, 'where' => $where);
-      break;
-    case 'vid':
-      
-      break;
-    }
+  if (count($tids)) {
+    // prevent users from seeing terms they do not have permission to read.
+    $tids = array_unique($tids); // avoid duplicates
+    $join = "LEFT JOIN {term_data} tac_td ON $primary_table.tid = tac_td.tid";
+    $where = "$primary_table.tid IN (". implode(', ', $tids) .") OR tac_td.vid NOT IN (". implode(',', $vids) .")"; 
+    
+    return array('join' => $join, 'where' => $where);
   }
 }
