Index: includes/database.inc
===================================================================
RCS file: /cvs/drupal/drupal/includes/database.inc,v
retrieving revision 1.56.2.2
diff -u -F^f -r1.56.2.2 database.inc
--- includes/database.inc	15 Nov 2006 21:51:38 -0000	1.56.2.2
+++ includes/database.inc	2 Jan 2007 20:33:05 -0000
@@ -283,31 +283,29 @@ function db_rewrite_sql($query, $primary
 
   if (!empty($where) || !empty($join)) {
     if (!empty($where)) {
-      $new = " WHERE $where ";
+      $new = "WHERE $where ";
     }
     $new = " $join $new";
-    if (strpos($query, 'WHERE')) {
-      $replace = 'WHERE';
-      $add = 'AND';
-    }
-    elseif (strpos($query, 'GROUP')) {
-      $replace = 'GROUP';
-      $add = 'GROUP';
-    }
-    elseif (strpos($query, 'ORDER')) {
-      $replace = 'ORDER';
-      $add = 'ORDER';
+
+    // Find the beginning of the WHERE clause and any clause after that.
+    $where_pos = strpos($query, 'WHERE');
+    ($other_pos = strpos($query, 'GROUP')) || ($other_pos = strpos($query, 'ORDER')) || ($other_pos = strpos($query, 'LIMIT'));
+
+    // Insert the new part into the query.
+    if ($where_pos && !empty($where)) {
+      if ($other_pos) {
+        $query = substr($query, 0, $where_pos) . $new .' AND ('. substr($query, $where_pos + 6, $other_pos - $where_pos - 7) .') '. substr($query, $other_pos);
+      }
+      else {
+        $query = substr($query, 0, $where_pos) . $new .' AND ('. substr($query, $where_pos + 6) .')';
+      }
     }
-    elseif (strpos($query, 'LIMIT')) {
-      $replace = 'LIMIT';
-      $add = 'LIMIT';
+    else if (($insert_pos = $where_pos) || ($insert_pos = $other_pos)) {
+      $query = substr($query, 0, $insert_pos) . $new . substr($query, $insert_pos);
     }
     else {
       $query .= $new;
     }
-    if (isset($replace)) {
-      $query = str_replace($replace, "$new $add ", $query);
-    }
   }
 
   return $query;
