From 2371381dfb4a6c3f76a9b3874e6667a65ac2874e Mon Sep 17 00:00:00 2001
From: Alex Athanasopoulos <filopodaros@gmail.com>
Date: Wed, 20 Jul 2011 11:57:06 +0000
Subject: [PATCH 1/2] Use References header, in addition to In-Reply-To

---
 femail.drush.inc |   14 +++++++++++++-
 1 files changed, 13 insertions(+), 1 deletions(-)

diff --git a/femail.drush.inc b/femail.drush.inc
index b1f77ad..cb10efa 100644
--- a/femail.drush.inc
+++ b/femail.drush.inc
@@ -145,6 +145,13 @@ function _femail_get_msg(){
     if(isset($part_data['headers']['in-reply-to'])){
       $msg['in-reply-to'] = $part_data['headers']['in-reply-to'];
     }
+    // Get the References header which may contain the original in-reply-to,
+	// in some cases where the mail is relayed.
+	// This happens when Amazon SES is used.
+    if(isset($part_data['headers']['references'])){
+	  $references = $part_data['headers']['references'];
+      $msg['references'] = preg_split( '/\s+/', $references );
+    }
   }
   if(!$body_is_set){
     // Looks like we have a none mime encoded message.  Here we need to loop
@@ -163,7 +170,12 @@ function _femail_post_comment($msg, $user, $status){
   // First we'll make sure the in-reply-to is in the msgid table, if not, we
   // will have to add this as a new thread.
   if(isset($msg['in-reply-to'])){
-    $result = db_query("SELECT cid, nid FROM {femail_msgs} WHERE msgid = '%s'", $msg['in-reply-to']);
+    $refs = array($msg['in-reply-to']);
+	if(isset($msg['references'])){
+	  $refs = array_merge( $refs, $msg['references']);
+	}
+    $result = db_query("SELECT cid, nid FROM {femail_msgs} WHERE msgid in (".
+		implode( ',', array_pad(array(), count($refs), "'%s'")) . ")", $refs ); 
   }else{
     // We need to select the nid and 0 as cid from node where title is the same
     // as the subject line (less "re:")
-- 
1.7.4.1


From de1410552870c77bd4c381e4adaa4b3ac9c3c04e Mon Sep 17 00:00:00 2001
From: Alex Athanasopoulos <filopodaros@gmail.com>
Date: Wed, 20 Jul 2011 12:39:45 +0000
Subject: [PATCH 2/2] uppercase SQL keyword.  Comments.

---
 femail.drush.inc |    3 ++-
 1 files changed, 2 insertions(+), 1 deletions(-)

diff --git a/femail.drush.inc b/femail.drush.inc
index cb10efa..c03dd60 100644
--- a/femail.drush.inc
+++ b/femail.drush.inc
@@ -174,7 +174,8 @@ function _femail_post_comment($msg, $user, $status){
 	if(isset($msg['references'])){
 	  $refs = array_merge( $refs, $msg['references']);
 	}
-    $result = db_query("SELECT cid, nid FROM {femail_msgs} WHERE msgid in (".
+	// query for all in-reply-to and references
+    $result = db_query("SELECT cid, nid FROM {femail_msgs} WHERE msgid IN (".
 		implode( ',', array_pad(array(), count($refs), "'%s'")) . ")", $refs ); 
   }else{
     // We need to select the nid and 0 as cid from node where title is the same
-- 
1.7.4.1

