--- mailhandler.module.org	2010-06-04 14:16:11.000000000 +0200
+++ mailhandler.module	2011-01-19 16:08:33.000000000 +0100
@@ -1,6 +1,43 @@
 <?php
-// $Id: mailhandler.module,v 1.96.2.29 2010/06/04 12:16:11 developmentseed Exp $
+// $Id: mailhandler.module,v 1.96.2.30 2010/08/04 18:10:25 developmentseed Exp $
 
+/**
+ * Implementation of hook_nodeapi().
+ * To make sure we can set the timstamp, create and changed to values we need if retroactivly insert data into the tables
+ * This is important incase you import old mailman archieves or other old timestamped data
+*/
+function mailhandler_nodeapi($node, $op, $teaser, $page) {
+  switch ($op) {
+    case 'presave':
+      //On create set the changed timestamp plus one(1) so changed time is a little higher then created which would be the case if data would have been manually added on a site
+      $node->changed = $node->created+1;
+      $node->timestamp = $node->changed;
+      break;
+    case 'update':
+      break;
+    case 'insert':
+      break;
+  }
+}
+
+/**
+ * Implementation of hook_comment nodeapi().
+ * To make sure we can set the timestamp, create and changed to values we need if retroactivly insert data into the tables
+ * This is important incase you import old mailman archieves and also if you want the data to have the timevalue of the email
+*/
+function mailhandler_comment_nodeapi($node, $op, $arg) {
+  switch ($op) {
+    case 'presave':
+      //On create set the changed timestamp plus one(1) so changed time is a little higher then created which would be the case if data would have been manually added on a site
+      $node->changed = $node->created+1;
+      $node->timestamp = $node->changed;
+      break;
+    case 'update':
+      break;
+    case 'insert':
+      break;
+  }
+}
 
 /**
  * Implementation of hook_cron(). Process msgs from all enabled mailboxes.
@@ -22,7 +59,6 @@ function mailhandler_perm() {
   return array('administer mailhandler');
 }
 
-
 /**
  * Implementation of hook_menu().
  */
@@ -120,7 +156,6 @@ function mailhandler_mailbox_load($mid) 
  */
 function mailhandler_help($path = 'admin/help#mailhandler', $arg) {
   $output = '';
-  $link->add = l(t('Add mailbox'), 'admin/content/mailhandler/add');
 
   // Gather examples of useful commands, and build a definition list with them:
   $commands[] = array('command' => 'taxonomy: [term1, term2]',
@@ -159,7 +194,7 @@ function mailhandler_help($path = 'admin
    ));
       $output .= '<h3 id="commands">'. t('Useful Commands') .'</h3>';
       $output .= $commands_list;
-      $output .= '<p>'. t('For more information please read the configuration and customization handbook <a href="@mailhandler">Mailhandler page</a>.', array('@mailhandler' => url('http://www.drupal.org/handbook/modules/mailhandler', array('absolute' => TRUE)))) .'</p>'; 
+      $output .= '<p>'. t('For more information please read the configuration and customization handbook <a href="@mailhandler">Mailhandler page</a>.', array('@mailhandler' => url('http://www.drupal.org/handbook/modules/mailhandler', array('absolute' => TRUE)))) .'</p>';
       return $output;
     case 'admin/content/mailhandler':
       return t('The mailhandler module allows registered users to create or edit nodes and comments via email. Authentication is usually based on the From: email address. There is also an email filter that can be used to prettify incoming email. Users may post taxonomy terms, teasers, and other node parameters using the Command capability.');
@@ -172,18 +207,16 @@ function mailhandler_help($path = 'admin
   }
 }
 
-
 /**
  * Fetch data for a specific mailbox from the database.
- * 
- * TODO: remove this callback now that we have mailhandler_mailbox_load which is also a menu loader, 
+ *
+ * TODO: remove this callback now that we have mailhandler_mailbox_load which is also a menu loader,
  * though, there are other modules that may depend on this legacy callback, like "mail comment"
  */
 function mailhandler_get_mailbox($mid) {
   return db_fetch_array(db_query("SELECT * FROM {mailhandler} WHERE mid = %d", $mid));
 }
 
-
 /**
  * Return a default content type if the user has not chosen a specific type on the settings page
  * In order of priority, return blog, story, page
@@ -226,10 +259,10 @@ function mailhandler_default_type() {
 
 /**
  * Run message retrieval and node processing on a mailbox - is a wrapper around mailhandler_retrieve
- * 
+ *
  * Batch API smashes the stack, so this function is called twice when fetching
  * messages via batch in order to return the results from the batch.
- * 
+ *
  * @param $mailbox
  *   Array of mailbox configuration
  * @param $mode
@@ -240,7 +273,8 @@ function mailhandler_default_type() {
  *   Array of retrieved messages
  */
 function mailhandler_node_process_mailbox($mailbox = FALSE, $mode = FALSE, $limit = FALSE, $messages = array()) {
-  if (empty($messages)) {
+
+if (empty($messages)) {
     if ($mode == 'ui') {
       mailhandler_retrieve($mailbox, $mode, $limit);
     }
@@ -256,7 +290,7 @@ function mailhandler_node_process_mailbo
     // See mailhandler_mailhandler_batch_results.  This hook is invoked
     // and mailhandler_process_mailbox is called a second time in order
     // to obtain the messages that were retrieved and continue processing.
-    // This is necessary because we cannot obtain the results back from 
+    // This is necessary because we cannot obtain the results back from
     // batch processing directly.
     foreach ($messages as $message) {
       mailhandler_node_process_message($message['header'], $message['origbody'], $message['mailbox'], $message['mimeparts']);
@@ -266,9 +300,9 @@ function mailhandler_node_process_mailbo
 
 /**
  * Implementation of hook_mailhandler_batch_results()
- * 
+ *
  * See mailhandler_process_mailbox()
- * 
+ *
  */
 function mailhandler_mailhandler_batch_results($results) {
   mailhandler_node_process_mailbox(FALSE, FALSE, FALSE, $results);
@@ -296,7 +330,7 @@ function mailhandler_node_process_messag
   // to create users
   mailhandler_switch_user($node->uid);
 
-  // modules may override node elements before submitting. they do so by returning the node.
+  // Other modules may override node elements before submitting. they do so by returning the node.
   foreach (module_list() as $name) {
     if (module_hook($name, 'mailhandler')) {
       $function = $name .'_mailhandler';
@@ -317,7 +351,7 @@ function mailhandler_node_process_messag
       $type = 'node';
     }
   }
-  
+
   // Invoke a second hook for modules to operate on the newly created/edited node/comment.
   foreach (module_list() as $name) {
     if (module_hook($name, 'mailhandler_post_save')) {
@@ -326,7 +360,7 @@ function mailhandler_node_process_messag
       $function($nid, $type);
     }
   }
-  
+
   // switch back to original user
   mailhandler_switch_user();
 
@@ -391,7 +425,7 @@ function mailhandler_node_prepare_messag
   // Manually set this to 0 since that's what the rest of the code expects.
   $node->uid = 0;
   // In order to fall back to the permission system for comment status, the status property must
-  // be unset if type is comment.  It will get set by explicit commands, and if not, by 
+  // be unset if type is comment.  It will get set by explicit commands, and if not, by
   // comment_save itself.
   if($node->type == 'comment') {
     unset($node->status);
@@ -413,19 +447,27 @@ function mailhandler_node_prepare_messag
   // decode encoded subject line
   $subjectarr = imap_mime_header_decode($header->subject);
   if (empty($subjectarr)) {
+    //TODO see what side effect this has on Listhandlers threading in last step if threading is done on subject
     $node->title = truncate_utf8(trim(decode_entities(strip_tags(check_markup($node->body)))), 29, TRUE);
   }
   else {
     for ($i = 0; $i < count($subjectarr); $i++) {
-      if ($subjectarr[$i]->charset != 'default')
+      if ($subjectarr[$i]->charset != 'default') //TODO: possibly not fully correct with old emails default was not UTF8
       $node->title .= drupal_convert_to_utf8($subjectarr[$i]->text, $subjectarr[$i]->charset);
       else
       $node->title .= $subjectarr[$i]->text;
     }
   }
-  $node->date = $node->changed = format_date($header->udate, 'custom', 'Y-m-d H:i:s O');
+
+  //the node creation will be the the emails timestamp
+  //TODO: Add a parameter of mailhandler GUI interface along the lines of use_emailtime Y/N so user can choose if the server cration time must be injected or the eamail time for OLD email imports this is important
+  //INFO: $header->udate is actually the time the email arrived into the email server of the sender for the first time not the date set at email sender client computer
+  //using udate is more correct in 99% of the scenarios
+  $node->created = $header->udate;
+  $node->timestamp = $header->udate; //The old way of pre D6.21 is using a timestamp
+  $node->date = format_date($header->udate, 'custom', 'Y-m-d H:i:s O'); //TODO: maybe timezone needs to be added and also "en", see drupal format_date
   $node->format = $mailbox['format'];
-  
+
   // If an nid command was supplied, and type is not 'comment', append the revision number
   if (isset($node->nid) && !empty($node->nid) && $node->type != 'comment') {
     $vid = db_result(db_query('SELECT n.vid FROM {node} n WHERE n.nid = %d', $node->nid));
@@ -443,7 +485,7 @@ function mailhandler_comment_submit($nod
   global $user;
   if (!$node->subject) $node->subject = $node->title;
   // When submitting comments, 'comment' means actualy the comment's body, and not the comments status for a node.
-  // We need to reset the comment's body, so it doesn't colide with a default 'comment' command. 
+  // We need to reset the comment's body, so it doesn't colide with a default 'comment' command.
   $node->comment = $node->body;
   // comment_save will not fall back to permission system if we set the status explicitly
   // See comment_save.  += will not overwrite an existing array property.
@@ -451,12 +493,18 @@ function mailhandler_comment_submit($nod
     // In comment module, status of 1 means unpublished, status of 0 means published.
     $node->status == 1 ? $node->status = 0 : $node->status = 1;
   }
+
   // We want the comment to have the email time, not the current time
+  //TODO: What to do if the issue is created does NOT have a value at all, then shoult it be current time or timestamp = 0(1970) I opt for 1970 then the date sort will be ok
+  $node->changed = $node->created ;
+  //Timestamp is depriciated need to set changed and created but we leave it in for backwards compatibility
   $node->timestamp = $node->created;
+
   // comment_save gets an array
   $edit = (array)$node;
 
   // post the comment. if unable, send a failure email when so configured
+
   $cid = comment_save($edit);
   if (!$cid && $mailbox['replies']) {
     // $fromaddress really refers to the mail header which is authoritative for authentication
@@ -466,7 +514,7 @@ function mailhandler_comment_submit($nod
     drupal_mail('mailhandler', 'mailhandler_error_comment', $fromaddress, user_preferred_language($user), $params);
     watchdog('mailhandler', 'Comment submission failure: %subject.', array('%subject' => $edit['subject']), WATCHDOG_ERROR);
   }
-  
+
   return $cid;
 }
 
@@ -507,7 +555,7 @@ function mailhandler_node_submit($node, 
     // Return the node is successfully saved
     if (!isset($error_text)) {
       return $node;
-    } 
+    }
   }
   else {
     $error_text = t('Your submission is invalid:');
@@ -520,7 +568,7 @@ function mailhandler_node_submit($node, 
       drupal_mail('mailhandler', 'mailhandler_error_node', $fromaddress, user_preferred_language($user), $params);
     }
   }
-  
+
   // return FALSE if the node was not successfully saved
   return FALSE;
 }
@@ -650,7 +698,7 @@ function mailhandler_mailhandler_authent
  * Authenticate message based on sender's email address
  *   If the sender's email address matches an email address of a valid user, then assign
  *   that user's uid and name to the node object.
- *   
+ *
  * @param $node
  *   Object a node object
  * @param $header
@@ -659,7 +707,7 @@ function mailhandler_mailhandler_authent
  *   String message body text
  * @param $mailbox
  *   Array of mailbox configuration
- * 
+ *
  * @return object, the node object
  */
 function mailhandler_authenticate_default($node, $header, $origbody, $mailbox) {
@@ -683,18 +731,18 @@ function mailhandler_authenticate_defaul
 
 /**
  * Authenticate message based on token from tokenauth module
- *   If the user's token is found somewhere in the "to" field, assign that user's uid and name 
+ *   If the user's token is found somewhere in the "to" field, assign that user's uid and name
  *   to the node object.  A rough search for the token somewhere in the "toaddress" is performed
  *   instead of an exact, ordered match in order to allow some freedom in the format of allowed
  *   "toaddress".  For example, if using a catchall email address, the toaddress could be:
- *   
+ *
  *   f93ksj35dx@example.com - where f93ksj35dx is the user's token
  *   or alternatively:
  *   f93ksj35dx-foo@example.com - where f93ksj35dx is the user's token and foo is the name of an
- *   Organic Group to which the message should be assigned.  
- *   
+ *   Organic Group to which the message should be assigned.
+ *
  *   A rough search allows for different approaches to use this single authentication method.
- *   
+ *
  * @param $node
  *   Object a node object
  * @param $header
@@ -703,7 +751,7 @@ function mailhandler_authenticate_defaul
  *   String message body text
  * @param $mailbox
  *   Array of mailbox configuration
- * 
+ *
  * @return object, the node object
  */
 function mailhandler_authenticate_tokenauth($node, $header, $origbody, $mailbox) {
@@ -732,7 +780,7 @@ function mailhandler_authenticate_tokena
 
 /**
  * Determine from address either using the mailbox setting or via the header information
- * 
+ *
  * @param $header
  *   Object message header information
  * @param $mailbox
@@ -766,16 +814,16 @@ function mailhandler_user_load($mail, $p
 
 /**
  * Look up a user based on their mailalias addresses
- * 
+ *
  * Helper function for mailhandler_authenticate_tokenauth()
- * 
+ *
  * @param $fromaddress
  *   String from address
  * @param $node
  *   Object node object
  * @param $mailbox
  *   Array of mailhandler mailbox configuration
- *   
+ *
  * @return Object user object or FALSE
  */
 function mailhandler_user_load_alias($fromaddress, $node, $mailbox) {
