=== modified file 'includes/database.inc'
--- includes/database.inc	2008-01-04 09:31:48 +0000
+++ includes/database.inc	2008-01-06 11:33:19 +0000
@@ -315,34 +315,28 @@ function db_rewrite_sql($query, $primary
   }
 
   if (!empty($where) || !empty($join)) {
-    if (!empty($where)) {
-      $new = "WHERE $where ";
-    }
-    $new = " $join $new";
-    if (strpos($query, 'WHERE')) {
-      $query = str_replace('WHERE', $new .'AND (', $query);
-      $insert = ') ';
-    }
-    else {
-      $insert = $new;
-    }
-    if (strpos($query, 'GROUP')) {
-      $replace = 'GROUP';
-    }
-    elseif (strpos($query, 'HAVING')) {
-      $replace = 'HAVING';
-    }
-    elseif (strpos($query, 'ORDER')) {
-      $replace = 'ORDER';
-    }
-    elseif (strpos($query, 'LIMIT')) {
-      $replace = 'LIMIT';
+    $pattern = '{
+      # Beginning of the string
+      ^
+      (?P<anonymous_view>
+        # Everything within this set of parentheses is named "anonymous view"
+        (?:
+          [^()]++                   # anything not parentheses
+        |
+          \( (?P>anonymous_view) \)          # an open parenthesis, more "anonymous view" and finally a close parenthesis.
+        )*
+      ).*WHERE
+    }x';
+    preg_match($pattern, $query, $matches);
+    $string = $matches['anonymous_view'] ? $matches['anonymous_view'] : $matches[0];
+    preg_match('/^(.+)WHERE/', $string, $matches);
+    if ($where) {
+      $query = $matches[1] ." $join WHERE $where AND ( ". substr($query, strlen($matches[1]) + 5);
+      preg_match('/^(.+)(?:GROUP|ORDER|LIMIT|$)/U', $query, $matches);
+      $query = $matches[1] .') ' . substr($query, strlen($matches[1]));
     }
     else {
-      $query .= $insert;
-    }
-    if (isset($replace)) {
-      $query = str_replace($replace, $insert . $replace, $query);
+      $query = $matches[1] ." $join ". substr($query, strlen($matches[1]));
     }
   }
 

