=== modified file 'includes/database.inc'
--- includes/database.inc	2008-01-04 09:31:48 +0000
+++ includes/database.inc	2008-01-06 23:50:15 +0000
@@ -315,34 +315,43 @@ 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);
+      // PHP 4 does not support strrpos for strings. We emulate it.
+      $query_reverse = strrev($query);
+      // No need to use strrev on the needle, we supply it reversed too.
+      foreach (array('GROUP' => 'PUORG', 'ORDER' => 'REDRO', 'LIMIT' => 'TIMIL') as $needle => $needle_reverse) {
+        $pos = strpos($query_reverse, $needle_reverse);
+        if ($pos !== FALSE) {
+          // All needles are five characters long.
+          $pos = $pos + 5;
+          break;
+        }
+      }
+      if ($pos !== FALSE) {
+        $query = substr($query, 0, -$pos) .')'. substr($query, -$pos);
+      }
+      else {
+        $query .= ')';
+      }
     }
     else {
-      $query .= $insert;
-    }
-    if (isset($replace)) {
-      $query = str_replace($replace, $insert . $replace, $query);
+      $query = $matches[1] ." $join ". substr($query, strlen($matches[1]));
     }
   }
 

