--- mail2web.module	2008-08-08 11:59:01.000000000 -0600
+++ mail2web_new.module	2009-01-03 15:51:58.000000000 -0700
@@ -119,12 +119,12 @@ function mail2web_mailbox_mail() {
  * 
  * Adds message headers into outgoing emails for notifications
  */
-function mail2web_message_alter(&$message, $info, $method) {
+function mail2web_message_alter(&$message, $info) {
   $params = array();
   // For now, just for non digested emails
-  if (!empty($message['notifications']) && ($account = $message['account']) 
-    && empty($message['notifications']['digest']) && $info['group'] == 'mail') {
-    $event = array_shift($message['notifications']['events']);
+  if (!empty($message->notifications) && ($account = $message->account) 
+    && empty($message->notifications['digest']) && $info['group'] == 'mail') {
+    $event = array_shift($message->notifications['events']);
     if ($event->type == 'node' && !empty($event->objects['node'])) {
       $params['uid'] = $account->uid;
       $params['nid'] = $event->objects['node']->nid;
@@ -135,20 +135,23 @@ function mail2web_message_alter(&$messag
   }
   // If we've got some params out of the message, embed them into the message id for emails only
   if ($params && ($reply = mail2web_mailbox_mail())) {
-    $message['params']['mail']['headers']['Message-ID'] = mail2web_build_messageid($params);
-    $message['params']['mail']['headers']['Reply-To'] = $reply;
+    $message->params['mail']['headers']['Message-ID'] = mail2web_build_messageid($params);
+    $message->params['mail']['headers']['Reply-To'] = $reply;
     // Add marker text into the message header part taking care of already existing text
     if ($text = variable_get('mail2web_reply_text', t('((( Reply ABOVE this LINE to POST a COMMENT )))'))) {
       $prefix = array($text);
-      if (!empty($message['body']['#prefix'])) {
-        $prefix[] = $message['body']['#prefix'];
+      if (!empty($message->body['#prefix'])) {
+        $prefix[] = $message->body['#prefix'];
       }
       // This glue text is a best guess, may cause trouble though, also with filtering (?).
       // So we better explicitly set glue text for all sending methods
       $info += array('glue' => "\n");
-      $message['body']['#prefix'] = implode($info['glue'], $prefix);
+      $message->body['#prefix'] = implode($info['glue'], $prefix);
+      //  This is a simple solution to mail clients that strip out the messageid and/or in-reply-to headers.
+      //  We insert the messageid in the footer to use as a back-up to the header info
+      //  see http://drupal.org/node/290214
+      $message->body['#footer'] .= t(' MessageID='.$message->params['mail']['headers']['Message-ID']);
     }
-    
   }
 }
 
@@ -156,8 +159,25 @@ function mail2web_message_alter(&$messag
  * Implementation of hook_mailhandler()
  */
 function mail2web_mailhandler($node, $result, $i, $header, $mailbox) {
+  //  Get vars so we can make sure we are working with a M2W mailbox
+  $mailbox_mid = variable_get('mail2web_mailbox', '');
+  $mbox = mailhandler_get_mailbox($mailbox_mid);
+  $mbox_name = $mbox['mail'];
   // The In-reply-to header is cleaned and passed in $node->threading
-  if ($node->threading && ($params = mail2web_check_messageparams($node->threading, $header)) && empty($params['error'])) {
+  // Check to see if the header info is present as it may have been stripped by some mail clients
+  // If it's not present check the email for backup signature
+  if (!$node->threading) { 
+     $node->threading = _mail2web_get_backup_messageid($node->body);
+  }
+  //  Some mail clients (iPhone) change the toaddress from example@example.com to "example@example.com"<example@example.com>
+  //  @TODO This may need to be addressed in mailhandler?
+  //  @TODO Should we be using strpos or stripos - I think we already have PHP 5 dependency?
+  //  Check to see if it starts with something like a double quote and if the mailbox name is in the string
+  if (strpos($header->toaddress, $mbox_name) != 0 && strpos($header->toaddress, $mbox_name) !== FALSE ) {
+	//  Just set it to the mailbox
+	$header->toaddress = $mbox_name;
+  }
+  if ($header->toaddress == $mbox_name && $node->threading && ($params = mail2web_check_messageparams($node->threading, $header)) && empty($params['error'])) {
     // Now check user id , just go ahead if they match and it is a valid user
     if ($node->uid && $node->uid == $params['uid']) {
       // Add params into the node object, other modules may use them
@@ -165,21 +185,21 @@ function mail2web_mailhandler($node, $re
       // Set comment parameters
       $node->type = 'comment';
       $node->nid = $params['nid'];
-      $node->pid = $params['cid'];
-      
-      // Now trim out the resf of the message if separator text exists
+      $node->pid = $params['cid'];     
+      // Now trim out the rest of the message if separator text exists
       // @ TODO May fail for html mails
       if ($marker = variable_get('mail2web_reply_text', t('((( Reply ABOVE this LINE to POST a COMMENT )))'))) {
         // Now the dirty part. May need some more clean up for line endings, spare html, etc...
         $pos = strpos($node->body, $marker);
         if ($pos !== FALSE) {
-          $node->body = substr($node->body, 0, $pos);
-          // Something specifically for mac mail clients out there
-          $split = preg_split("/On [A-Z][a-z]{2} [0-9]{1,2}, [0-9]{4}, at [0-9]{1,2}:[0-9]{2} [AP]M, [a-zA-Z0-9._%-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4} wrote/",$node->body);
-          $split = preg_split("/\>/",$split[0]);
-          $node->body = $split[0];
+          // Mailhandler brings this in as a full node with teaser/body but we need to chnage context to comment
+          $node->comment = substr($node->body, 0, $pos);
         }
       }
+      // Comments do not need overhead of node teaser or body past this point.
+      $node->body = '';
+      $node->teaser = '';
+      //  We return the "node" but it will be saved in mailhandler as a comment
       return $node;
     } else {
       // Users in parameters and mail don't match
@@ -188,12 +208,16 @@ function mail2web_mailhandler($node, $re
   } 
   // If we reach here, there has been an error. Check error code or send a generic one.
   // This part doesn't return a node so it won't be further processed by mailhandler
-  if ($params) {
+  if ($header->toaddress == $mbox_name && $params) {
     mail2web_error($params['error'], $node, $header);
-  } else {
+  } 
+  elseif ($header->toaddress == $mbox_name && !$params) {
     mail2web_error(MAIL2WEB_ERROR_PARAMS, $node, $header);
   }
-
+  // If the message is not addressed to the mail2web mailbox, give the node back to mailhander for delegation.
+  elseif ($header->toaddress != $mbox_name) {
+    return $node;
+  }
 }
 
 /**
@@ -376,3 +400,30 @@ function mail2web_signature($params) {
   return md5(implode('-', $params));
 }
 
+ /**
+ * Find the message id in the body if mail client stripped it out of the headers.
+ *  
+ * @param $body
+ *   raw email body
+ *
+ */
+function _mail2web_get_backup_messageid($body) {
+  if (preg_match("/([0-9]+\.){4}+[a-z0-9]+@([a-z0-9-]+\.[a-z]{2,5})/i",$body,$matches)) {
+  	//  Check to make sure the match has our mail2web domain
+    $domain = variable_get('mail2web_server_string', 'example.com');
+	if ($matches[2] == $domain) {
+      $backup_messageid = $matches[0];
+      // We have a match for the messageid and the mail2web domain string so we are good
+      return $backup_messageid;   	
+	}
+  }	
+  else {
+	// No matches found so assume we have no messageid and node->threading is not set
+    return FALSE;
+  }  
+}  
+
+   
+
+
+
