Fix another regression caused by 805eddaefd9503b5dbbd924bd6da66e29c4768f3

Also added a unit test for #4431
diff --git a/system/database/DB_query_builder.php b/system/database/DB_query_builder.php
index b46730e..66ef913 100644
--- a/system/database/DB_query_builder.php
+++ b/system/database/DB_query_builder.php
@@ -542,7 +542,7 @@
 				$s = $m[0][$i][1] + strlen($m[0][$i][0]), $i++)
 			{
 				$temp = substr($cond, $s, ($m[0][$i][1] - $s));
-				$newcond .= preg_match("/(.*)([\[\]\w\.'-]+)(\s*[^\"\[`'\w]+\s*)(.+)/i", $temp, $match)
+				$newcond .= preg_match("/(\(*)?([\[\]\w\.'-]+)(\s*[^\"\[`'\w]+\s*)(.+)/i", $temp, $match)
 						? $match[1].$this->protect_identifiers($match[2]).$match[3].$this->protect_identifiers($match[4])
 						: $temp;
 
@@ -552,9 +552,9 @@
 			$cond = ' ON '.$newcond;
 		}
 		// Split apart the condition and protect the identifiers
-		elseif ($escape === TRUE && preg_match("/([\[\]\w\.'-]+)(\s*[^\"\[`'\w]+\s*)(.+)/i", $cond, $match))
+		elseif ($escape === TRUE && preg_match("/(\(*)?([\[\]\w\.'-]+)(\s*[^\"\[`'\w]+\s*)(.+)/i", $cond, $match))
 		{
-			$cond = ' ON '.$this->protect_identifiers($match[1]).$match[2].$this->protect_identifiers($match[3]);
+			$cond = ' ON '.$match[1].$this->protect_identifiers($match[2]).$match[3].$this->protect_identifiers($match[4]);
 		}
 		elseif ( ! $this->_has_operator($cond))
 		{
diff --git a/tests/codeigniter/database/query_builder/join_test.php b/tests/codeigniter/database/query_builder/join_test.php
index 25bd4ac..58cb214 100644
--- a/tests/codeigniter/database/query_builder/join_test.php
+++ b/tests/codeigniter/database/query_builder/join_test.php
@@ -55,4 +55,24 @@
 		$this->assertEquals($expected, $result);
 	}
 
+	// ------------------------------------------------------------------------
+
+	public function test_join_escape_multiple_conditions_with_parentheses()
+	{
+		// We just need a valid query produced, not one that makes sense
+		$fields = array($this->db->protect_identifiers('table1.field1'), $this->db->protect_identifiers('table2.field2'));
+
+		$expected = 'SELECT '.implode(', ', $fields)
+				."\nFROM ".$this->db->escape_identifiers('table1')
+				."\nRIGHT JOIN ".$this->db->escape_identifiers('table2').' ON '.implode(' = ', $fields)
+				.' AND ('.$fields[0]." = 'foo' OR ".$fields[1].' = 0)';
+
+		$result = $this->db->select('table1.field1, table2.field2')
+				->from('table1')
+				->join('table2', "table1.field1 = table2.field2 AND (table1.field1 = 'foo' OR table2.field2 = 0)", 'RIGHT')
+				->get_compiled_select();
+
+		$this->assertEquals($expected, $result);
+	}
+
 }
\ No newline at end of file