diff --git a/modules/og_mailinglist_flag/og_mailinglist_flag.info b/modules/og_mailinglist_flag/og_mailinglist_flag.info
index d766e21..6c4e03d 100644
--- a/modules/og_mailinglist_flag/og_mailinglist_flag.info
+++ b/modules/og_mailinglist_flag/og_mailinglist_flag.info
@@ -3,4 +3,9 @@ description = "Integrates Og Mailinglist with the Flag module to provide a simpl
 dependencies[] = og_mailinglist
 dependencies[] = flag
 package = "Organic groups"
-core = "6.x"
+core = 7.x
+
+
+
+files[] = og_mailinglist_flag.install
+files[] = og_mailinglist_flag.module
diff --git a/modules/og_mailinglist_flag/og_mailinglist_flag.install b/modules/og_mailinglist_flag/og_mailinglist_flag.install
index 64994c6..c65c352 100644
--- a/modules/og_mailinglist_flag/og_mailinglist_flag.install
+++ b/modules/og_mailinglist_flag/og_mailinglist_flag.install
@@ -1,7 +1,13 @@
 <?php
+/**
+ * @file
+ * Install, update and uninstall functions for the og_mailinglist_flag module.
+ *
+ */
+
 
 /**
- * Implementation of hook_install().
+ * Implements hook_install().
  */
 function og_mailinglist_flag_install() {
   drupal_set_message("OG Mailinglist Flags ships with a default flag. You'll almost certainly need to edit it at /admin/build/flags to make it suitable for your needs. The two big things are giving permission to roles to use the flags and choosing which content types can be 'followed'. Also, there's a utility function available in og_mailinglist_flag.install for adding flags for all subscriptions made for nodes created in the past month");
@@ -27,7 +33,10 @@ function og_mailinglist_flag_add_flags() {
                          FROM {node} n
                          INNER JOIN {og_mailinglist_thread} o
                          ON n.nid = o.nid
-                         WHERE o.uid = %d", $uid);
+                         WHERE o.uid = :o.uid", array(':o.uid' => : o . uid, '' => array(
+        ':o.uid' => : o . uid,
+        '' => array(':o.uid' => $uid),
+      )));
 
     $nids = array();
     while ($info = db_fetch_array($result)) {
diff --git a/modules/og_mailinglist_flag/og_mailinglist_flag.module b/modules/og_mailinglist_flag/og_mailinglist_flag.module
index 5637ad6..485e5ae 100644
--- a/modules/og_mailinglist_flag/og_mailinglist_flag.module
+++ b/modules/og_mailinglist_flag/og_mailinglist_flag.module
@@ -1,7 +1,7 @@
 <?php
 
 /**
- * Implementation of hook_og_mailinglist_save_thread_subscription().
+ * Implements hook_og_mailinglist_save_thread_subscription().
  *
  * Flag the node for the user when they subscribe to a node.
  **/
@@ -11,7 +11,7 @@ function og_mailinglist_flag_og_mailinglist_save_thread_subscription($nid, $uid)
 }
 
 /**
- * Implementation of hook_og_mailinglist_delete_thread_subscription().
+ * Implements hook_og_mailinglist_delete_thread_subscription().
  *
  * When a thread subscription is deleted, unflag the node as well.
  **/
@@ -21,7 +21,7 @@ function og_mailinglist_flag_og_mailinglist_delete_thread_subscription($nid, $ui
 }
 
 /**
- * Implementation of hook_flag().
+ * Implements hook_flag().
  **/
 function og_mailinglist_flag_flag($action, $flag, $content_id, $account) {
   if ($flag->name == "follow_node") {
@@ -32,24 +32,23 @@ function og_mailinglist_flag_flag($action, $flag, $content_id, $account) {
 
       case 'unflag':
         og_mailinglist_delete_thread_subscription($content_id, $account->uid);
-        break;  
+        break;
     }
   }
 }
 
 /**
- * Implementation of hook_flag_default_flags().
+ * Implements hook_flag_default_flags().
  **/
 function og_mailinglist_flag_flag_default_flags() {
   $flags = array();
   // Exported flag: "Follow Node".
-  $flags[] = array (
+  $flags[] = array(
     'content_type' => 'node',
     'name' => 'follow_node',
     'title' => 'Follow Node',
     'global' => '0',
-    'types' => 
-    array (
+    'types' => array(
       0 => 'poll',
       1 => 'note',
       2 => 'job_form',
@@ -64,15 +63,12 @@ function og_mailinglist_flag_flag_default_flags() {
     'unflag_message' => '',
     'unflag_denied_text' => '',
     'link_type' => 'toggle',
-    'roles' => 
-    array (
-      'flag' => 
-      array (
+    'roles' => array(
+      'flag' => array(
         0 => 2,
         1 => 3,
       ),
-      'unflag' => 
-      array (
+      'unflag' => array(
         0 => 2,
         1 => 3,
       ),
diff --git a/modules/og_mailinglist_og_forum/og_mailinglist_og_forum.info b/modules/og_mailinglist_og_forum/og_mailinglist_og_forum.info
index 8df96bb..65b731e 100644
--- a/modules/og_mailinglist_og_forum/og_mailinglist_og_forum.info
+++ b/modules/og_mailinglist_og_forum/og_mailinglist_og_forum.info
@@ -3,4 +3,7 @@ description = "Integrates Og Mailinglist with OG Forum so that incoming emails w
 dependencies[] = og_mailinglist
 dependencies[] = og_forum
 package = "Organic groups"
-core = "6.x"
+core = 7.x
+
+
+files[] = og_mailinglist_og_forum.module
diff --git a/modules/og_mailinglist_og_forum/og_mailinglist_og_forum.module b/modules/og_mailinglist_og_forum/og_mailinglist_og_forum.module
index e418c43..a5b645e 100644
--- a/modules/og_mailinglist_og_forum/og_mailinglist_og_forum.module
+++ b/modules/og_mailinglist_og_forum/og_mailinglist_og_forum.module
@@ -1,31 +1,38 @@
 <?php
 
 /**
- * Implementation of hook_og_mailinglist_save_node_alter().
+ * Implements hook_og_mailinglist_save_node_alter().
  */
 function og_mailinglist_og_forum_og_mailinglist_save_node_alter(&$node) {
   // If this is a forum post and the og_forum module is enabled, find this group's
   // default forum container and add that to the node object.
   if ($node->type == "forum" && module_exists('og_forum')) {
-    // The "t.weight <> 0" is a hack essentially. og_term doesn't give any good way 
+    // The "t.weight <> 0" is a hack essentially. og_term doesn't give any good way
     // of finding out which term is actually an og_forum term and which isn't.
     // But it seems to change the weight of all legit forums to something other
-    // than 0 (-10 in most (all) cases) (I'm guessing a lot here). Anyways, don't 
+    // than 0 (-10 in most (all) cases) (I'm guessing a lot here). Anyways, don't
     // argue with what works.
-    $forum_id = db_result(db_query("SELECT o.tid
+    $forum_id = db_query("SELECT o.tid
                                     FROM {og_term} o
-                                    JOIN {term_data} t
+                                    JOIN {taxonomy_term_data} t
                                     ON o.tid = t.tid
-                                    WHERE o.nid = %d
-                                    AND t.weight <> 0", current($node->og_groups)));
-    $term = taxonomy_get_term($forum_id);
-    if(empty($node->tid)) {
+                                    WHERE o.nid = :o.nid
+                                    AND t.weight <> :t.weight", array(':o.nid' => : o . nid, ':t.weight' => : t . weight, '' => array(
+        ':o.nid' => : o . nid,
+        ':t.weight' => : t . weight,
+        '' => array(
+          ':o.nid' => current($node->og_groups),
+          ':t.weight' => 0,
+        ),
+      )))->fetchField();
+    $term = taxonomy_term_load($forum_id);
+    if (empty($node->tid)) {
       $node->tid = $term->tid;
     }
-    if(empty($node->vid)) {
+    if (empty($node->vid)) {
       $node->vid = $term->vid;
     }
-    if(empty($node->taxonomy)) {
+    if (empty($node->taxonomy)) {
       $node->taxonomy = array($term->vid => $term);
     }
   }
diff --git a/og_mailinglist.info b/og_mailinglist.info
index 6af8781..6933c30 100644
--- a/og_mailinglist.info
+++ b/og_mailinglist.info
@@ -3,7 +3,32 @@ name = OG Mailinglist
 description = "Allows email submissions of new posts and comments for organic groups."
 dependencies[] = og
 package = "Organic groups"
-core = "6.x"
+core = 7.x
 
 version = "6.x-1.0"
-core = "6.x"
+core = 7.x
+
+
+
+
+
+
+
+
+
+
+
+
+
+files[] = migrate_notifications_og_mailinglist.php
+files[] = og_mailinglist.install
+files[] = og_mailinglist.module
+files[] = og_mailinglist_api.inc
+files[] = og_mailinglist_digest_email.inc
+files[] = og_mailinglist_filter.inc
+files[] = og_mailinglist_phpmailer.inc
+files[] = og_mailinglist_transport.inc
+files[] = og_mailinglist_utilities.inc
+files[] = exim_og_mailinglist/og_mailinglist_exim4_transport.php
+files[] = postfix_og_mailinglist/og_mailinglist_postfix_transport.php
+files[] = testing/testing_mailer_integration.php
diff --git a/og_mailinglist.install b/og_mailinglist.install
index e5b8f53..1616820 100644
--- a/og_mailinglist.install
+++ b/og_mailinglist.install
@@ -1,37 +1,51 @@
 <?php
+/**
+ * @file
+ * Install, update and uninstall functions for the og_mailinglist module.
+ *
+ */
+
 // $Id$
-include_once 'og_mailinglist_utilities.inc'; //Load our utilities so the hook_requirements can call those functions.
+include_once DRUPAL_ROOT . '/' . 'og_mailinglist_utilities.inc'; //Load our utilities so the hook_requirements can call those functions.
 /**
- * Implementation of hook_install().
+ * Implements hook_install().
  */
 function og_mailinglist_install() {
-  $success = drupal_install_schema('og_mailinglist');
-  
   // Add any previously created groups to og_mailinglist.
   add_groups_to_og_mailinglist();
-  
-  if ($success) {
-    drupal_set_message(st('OG Mailinglist module installed tables successfully.'));
-  }
-  else {
-    drupal_set_message(st('The installation of the OG Mailinglist tables failed.'), 'error');
-  }
-    
+
+  drupal_set_message(st('OG Mailinglist module installed tables successfully.'));
+
   // Set OGM's system weight to be after Pathauto so our email footers always use the correct path.
-  $weight = db_result(db_query("SELECT weight FROM {system} WHERE type = 'module' AND name = 'pathauto'"));
+  $weight = db_query("SELECT weight FROM {system} WHERE type = :type AND name = :name", array(':type' => : type, ':name' => : name, '' => array(
+      ':type' => : type,
+      ':name' => : name,
+      '' => array(
+        ':type' => 'module',
+        ':name' => 'pathauto',
+      ),
+    )))->fetchField();
   if (!empty($weight)) {
-    db_query("UPDATE {system} SET weight = %d WHERE type = 'module' AND name = 'og_mailinglist'", $weight + 1);
+    db_update('system')
+      ->fields(array(
+      'weight' => $weight + 1,
+    ))
+      ->condition('type', 'module')
+      ->condition('name', 'og_mailinglist')
+      ->execute();
   }
 }
 
 /**
- * Implementation of hook_uninstall().
+ * Implements hook_uninstall().
  */
 function og_mailinglist_uninstall() {
-  drupal_uninstall_schema('og_mailinglist');
-  $result = db_query("SELECT name FROM {variable} WHERE name LIKE 'og_mailinglist_%'");
-  while ($row = db_fetch_object($result)) {
-    variable_del($row->name);
+  $result = db_query('variable')
+    ->fields('name')
+    ->condition('name', 'og_mailinglist_%', 'LIKE')
+    ->execute();
+  foreach ($result as $record) {
+    variable_del($record->fetchObject->name);
   }
 
   drupal_set_message(t('OG Mailinglist has been uninstalled.'));
@@ -55,7 +69,7 @@ function og_mailinglist_requirements($phase) {
       $requirements['og_mailinglist_phpmailer']['description'] = t('The <a href="@phpmailer">PHPMailer</a> library is missing or not installed correctly. <a href="@download">Download</a> and extract it to your <em>og_mailinglist</em> module directory. See the INSTALL.txt file for more information at path/to/drupal@install.', array('@phpmailer' => 'http://phpmailer.worxware.com/index.php?pg=phpmailer', '@download' => 'http://sourceforge.net/projects/phpmailer/files/phpmailer%20for%20php5_6/', '@install' => url(drupal_get_path('module', 'og_mailinglist') . '/INSTALL.txt')));
       $requirements['og_mailinglist_phpmailer']['severity'] = REQUIREMENT_ERROR;
     }
-    
+
     //Check for the Mail_mimeDecode library.
     og_mailinglist_mimeDecode_load_library();
     $requirements['og_mailinglist_mimeDecode']['title'] = t('Mail_mimeDecode PEAR extension');
@@ -75,166 +89,184 @@ function og_mailinglist_requirements($phase) {
 }
 
 /**
- * Implementation of hook_schema().
+ * Implements hook_schema().
  */
 function og_mailinglist_schema() {
- $schema = array();
- 
- $schema['og_mailinglist'] = array(
-  'fields' => array(
-   'nid' => array(
-     'description' => 'The nid for the new posting.',
-     'type' => 'int',
-     'unsigned' => TRUE,
-     'not null' => TRUE,
-     'default' => 0),
-    'group_email' => array(
-     'description' => 'The machine/email readable version of the group. Uses purl shortcode if available.',
-     'type' => 'varchar',
-     'length' => '255',
-     'not null' => TRUE,
-     'default' => ''),
-   ),
-   'primary key' => array('nid'),
- );
- 
- $schema['og_mailinglist_source'] = array(
-   'fields' => array(
-     'nid' => array(
-       'description' => 'The nid for the new posting.',
-       'type' => 'int',
-       'unsigned' => TRUE,
-       'not null' => TRUE,
-       'default' => 0),
-     'cid' => array(
-       'description' => 'The cid for the new posting. If 0, means posting was a new node not comment.',
-       'type' => 'int',
-       'unsigned' => TRUE,
-       'not null' => TRUE,
-       'default' => 0),
-     'source' => array(
-       'type' => 'varchar',
-       'description' => 'If the new posting was via email or the web. Should be either "email" or "web"',
-       'length' => '64',
-       'not null' => TRUE,
-       'default' => ''),
-     'message_id' => array(
-       'type' => 'varchar',
-       'description' => 'The message-id field of this post, either
+  $schema = array();
+
+  $schema['og_mailinglist'] = array(
+    'fields' => array(
+      'nid' => array(
+        'description' => 'The nid for the new posting.',
+        'type' => 'int',
+        'unsigned' => TRUE,
+        'not null' => TRUE,
+        'default' => 0,
+      ),
+      'group_email' => array(
+        'description' => 'The machine/email readable version of the group. Uses purl shortcode if available.',
+        'type' => 'varchar',
+        'length' => '255',
+        'not null' => TRUE,
+        'default' => '',
+      ),
+    ),
+    'primary key' => array('nid'),
+  );
+
+  $schema['og_mailinglist_source'] = array(
+    'fields' => array(
+      'nid' => array(
+        'description' => 'The nid for the new posting.',
+        'type' => 'int',
+        'unsigned' => TRUE,
+        'not null' => TRUE,
+        'default' => 0,
+      ),
+      'cid' => array(
+        'description' => 'The cid for the new posting. If 0, means posting was a new node not comment.',
+        'type' => 'int',
+        'unsigned' => TRUE,
+        'not null' => TRUE,
+        'default' => 0,
+      ),
+      'source' => array(
+        'type' => 'varchar',
+        'description' => 'If the new posting was via email or the web. Should be either "email" or "web"',
+        'length' => '64',
+        'not null' => TRUE,
+        'default' => '',
+      ),
+      'message_id' => array(
+        'type' => 'varchar',
+        'description' => 'The message-id field of this post, either
         from the email or auto-generated',
-       'non null' => TRUE,
-       'default' => 0,
-       'length' => 255),
-     'in_reply_to' => array(
-       'type' => 'varchar',
-       'description' => 'The in-reply-to header of this email, either
+        'non null' => TRUE,
+        'default' => 0,
+        'length' => 255,
+      ),
+      'in_reply_to' => array(
+        'type' => 'varchar',
+        'description' => 'The in-reply-to header of this email, either
         from the email or implied from the comment.',
-       'non null' => TRUE,
-       'default' => 0,
-       'length' => 255),
-     'references_header' => array(
-       'type' => 'varchar',
-       'description' => 'The reference header of this post.
+        'non null' => TRUE,
+        'default' => 0,
+        'length' => 255,
+      ),
+      'references_header' => array(
+        'type' => 'varchar',
+        'description' => 'The reference header of this post.
         If it originated from the web, this stores the references + message-id
         of its parent. We use the ungainly title of references_header as references appears
         to be a reserved word for MySQL',
-       'non null' => TRUE,
-       'default' => 0,
-       'length' => 512),
-     'parent_message_id' => array(
-       'type' => 'varchar',
-       'description' => 'The message-id of the parent of this post.',
-       'non null' => TRUE,
-       'default' => 0,
-       'length' => 255),
-   ),
-   'primary key' => array('nid', 'cid'),
-   'indexes' => array(
-     'source' => array('source'),
-     'message_id' => array('message_id'),
-   ),
- );
-
- $schema['og_mailinglist_thread'] = array(
-   'fields' => array(
-     'nid' => array(
-       'description' => 'The nid of the thread.',
-       'type' => 'int',
-       'unsigned' => TRUE,
-       'not null' => TRUE,
-       'default' => 0),
-     'uid' => array(
-       'description' => 'The uid of the user who\'s subscribed to this thead.',
-       'type' => 'int',
-       'unsigned' => TRUE,
-       'not null' => TRUE,
-       'default' => 0),
-   ),
-   'primary key' => array('nid', 'uid'),
-   'indexes' => array(
-     'nid' => array('nid'),
-     'uid' => array('uid'),
-   ),
- );
-
- $schema['og_mailinglist_subscription'] = array(
-   'fields' => array(
-     'nid' => array(
-       'description' => 'The nid of the Group.',
-       'type' => 'int',
-       'unsigned' => TRUE,
-       'not null' => TRUE,
-       'default' => 0),
-     'uid' => array(
-       'description' => 'The uid of the User.',
-       'type' => 'int',
-       'unsigned' => TRUE,
-       'not null' => TRUE,
-       'default' => 0),
-     'subscription_type' => array(
-       'type' => 'varchar',
-       'description' => 'Subscription type, e.g. "no email", "digest email", or "email"',
-       'length' => '128',
-       'not null' => TRUE,
-       'default' => ''
-     ),
-   ),
-   'primary key' => array('nid', 'uid'),
-   'indexes' => array(
-     'uid' => array('uid'),
-     'subscription_type' => array('subscription_type'),
-   ),
- );
- 
- return $schema;
+        'non null' => TRUE,
+        'default' => 0,
+        'length' => 512,
+      ),
+      'parent_message_id' => array(
+        'type' => 'varchar',
+        'description' => 'The message-id of the parent of this post.',
+        'non null' => TRUE,
+        'default' => 0,
+        'length' => 255,
+      ),
+    ),
+    'primary key' => array('nid', 'cid'),
+    'indexes' => array(
+      'source' => array('source'),
+      'message_id' => array('message_id'),
+    ),
+  );
+
+  $schema['og_mailinglist_thread'] = array(
+    'fields' => array(
+      'nid' => array(
+        'description' => 'The nid of the thread.',
+        'type' => 'int',
+        'unsigned' => TRUE,
+        'not null' => TRUE,
+        'default' => 0,
+      ),
+      'uid' => array(
+        'description' => 'The uid of the user who\'s subscribed to this thead.',
+        'type' => 'int',
+        'unsigned' => TRUE,
+        'not null' => TRUE,
+        'default' => 0,
+      ),
+    ),
+    'primary key' => array('nid', 'uid'),
+    'indexes' => array(
+      'nid' => array('nid'),
+      'uid' => array('uid'),
+    ),
+  );
+
+  $schema['og_mailinglist_subscription'] = array(
+    'fields' => array(
+      'nid' => array(
+        'description' => 'The nid of the Group.',
+        'type' => 'int',
+        'unsigned' => TRUE,
+        'not null' => TRUE,
+        'default' => 0,
+      ),
+      'uid' => array(
+        'description' => 'The uid of the User.',
+        'type' => 'int',
+        'unsigned' => TRUE,
+        'not null' => TRUE,
+        'default' => 0,
+      ),
+      'subscription_type' => array(
+        'type' => 'varchar',
+        'description' => 'Subscription type, e.g. "no email", "digest email", or "email"',
+        'length' => '128',
+        'not null' => TRUE,
+        'default' => '',
+      ),
+    ),
+    'primary key' => array('nid', 'uid'),
+    'indexes' => array(
+      'uid' => array('uid'),
+      'subscription_type' => array('subscription_type'),
+    ),
+  );
+
+  return $schema;
 }
 
 /**
  * Create the og_mailinglist table.
  */
 function og_mailinglist_update_6000() {
- // Create table.
- $ret = array();
- $schema['og_mailinglist'] = array(
-  'fields' => array(
-   'nid' => array(
-     'description' => 'The nid for the new posting.',
-     'type' => 'int',
-     'unsigned' => TRUE,
-     'not null' => TRUE,
-     'default' => 0),
-    'group_email' => array(
-     'description' => 'The machine/email readable version of the group. Uses purl shortcode if available.',
-     'type' => 'varchar',
-     'length' => '255',
-     'not null' => TRUE,
-     'default' => ''),
-   ),
-   'primary key' => array('nid'),
- );
- db_create_table($ret, 'og_mailinglist', $schema['og_mailinglist']);
- 
- return $ret;
+  // Create table.
+  $ret = array();
+  $schema['og_mailinglist'] = array(
+    'fields' => array(
+      'nid' => array(
+        'description' => 'The nid for the new posting.',
+        'type' => 'int',
+        'unsigned' => TRUE,
+        'not null' => TRUE,
+        'default' => 0,
+      ),
+      'group_email' => array(
+        'description' => 'The machine/email readable version of the group. Uses purl shortcode if available.',
+        'type' => 'varchar',
+        'length' => '255',
+        'not null' => TRUE,
+        'default' => '',
+      ),
+    ),
+    'primary key' => array('nid'),
+  );
+  db_create_table();
+
+  // hook_update_N() no longer returns a $ret array. Instead, return
+  // nothing or a translated string indicating the update ran successfully.
+  // See http://drupal.org/node/224333#update_sql.
+  return t('TODO Add a descriptive string here to show in the UI.') /* t('OG Mailing List Update 6000 executed') */;
 }
 
 /**
@@ -249,14 +281,18 @@ function og_mailinglist_update_6001() {
  */
 function og_mailinglist_update_6002() {
   $ret = array();
- 
-  db_drop_field($ret, 'og_mailinglist_subscription', 'space_type');
-  db_change_field($ret, 'og_mailinglist_subscription', 'sid', 'nid', array(
-                           'type' => 'int',
-                           'not null' => TRUE,
-                           'default' => 0));
-  
-  return $ret;
+
+  db_drop_field();
+  db_change_field('nid', array(
+    'type' => 'int',
+    'not null' => TRUE,
+    'default' => 0,
+  ));
+
+  // hook_update_N() no longer returns a $ret array. Instead, return
+  // nothing or a translated string indicating the update ran successfully.
+  // See http://drupal.org/node/224333#update_sql.
+  return t('TODO Add a descriptive string here to show in the UI.') /* t('OG Mailinglist update 6002 executed') */;
 }
 
 /**
@@ -266,39 +302,46 @@ function og_mailinglist_update_6002() {
 function og_mailinglist_update_6003() {
   $ret = array();
 
-  db_add_field($ret, 'og_mailinglist_source', 'message_id', array(
-                'type' => 'varchar',
-                'description' => 'The message-id field of this post, either
+  db_add_field(array(
+    'type' => 'varchar',
+    'description' => 'The message-id field of this post, either
                 from the email or auto-generated',
-                'non null' => TRUE,
-                'default' => 0,
-                'length' => 255));
+    'non null' => TRUE,
+    'default' => 0,
+    'length' => 255,
+  ));
 
-  db_add_field($ret, 'og_mailinglist_source', 'in_reply_to', array(
-                'type' => 'varchar',
-                'description' => 'The in-reply-to header of this email, either
+  db_add_field(array(
+    'type' => 'varchar',
+    'description' => 'The in-reply-to header of this email, either
                 from the email or implied from the comment.',
-                'non null' => TRUE,
-                'default' => 0,
-                'length' => 255));
+    'non null' => TRUE,
+    'default' => 0,
+    'length' => 255,
+  ));
 
-  db_add_field($ret, 'og_mailinglist_source', 'references', array(
-                'type' => 'varchar',
-                'description' => 'The reference header of this post.
+  db_add_field(array(
+    'type' => 'varchar',
+    'description' => 'The reference header of this post.
                 If it originated from the web, this stores the references + message-id
                 of its parent.',
-                'non null' => TRUE,
-                'default' => 0,
-                'length' => 512));
-
-  db_add_field($ret, 'og_mailinglist_source', 'parent_message_id', array(
-                'type' => 'varchar',
-                'description' => 'The message-id of the parent of this post.',
-                'non null' => TRUE,
-                'default' => 0,
-                'length' => 255));
-
-  return $ret;
+    'non null' => TRUE,
+    'default' => 0,
+    'length' => 512,
+  ));
+
+  db_add_field(array(
+    'type' => 'varchar',
+    'description' => 'The message-id of the parent of this post.',
+    'non null' => TRUE,
+    'default' => 0,
+    'length' => 255,
+  ));
+
+  // hook_update_N() no longer returns a $ret array. Instead, return
+  // nothing or a translated string indicating the update ran successfully.
+  // See http://drupal.org/node/224333#update_sql.
+  return t('TODO Add a descriptive string here to show in the UI.') /* t('OG MailingList Update 6003 executed') */;
 }
 
 /**
@@ -307,45 +350,72 @@ function og_mailinglist_update_6003() {
 function og_mailinglist_update_6004() {
   $ret = array();
 
-  db_change_field($ret, 'og_mailinglist_source', 'references', 'references_header', array(
-                     'type' => 'varchar',
-                     'non null' => TRUE,
-                     'default' => 0,
-                     'length' => 512)
+  db_change_field('references_header', array(
+    'type' => 'varchar',
+    'non null' => TRUE,
+    'default' => 0,
+    'length' => 512,
+  )
   );
 
-  return $ret;
+  // hook_update_N() no longer returns a $ret array. Instead, return
+  // nothing or a translated string indicating the update ran successfully.
+  // See http://drupal.org/node/224333#update_sql.
+  return t('TODO Add a descriptive string here to show in the UI.') /* t('OG MailingList Update 6004 executed') */;
 }
 
 /**
-* Change module weight to ensure we fire after pathauto if its present.
-*/
+ * Change module weight to ensure we fire after pathauto if its present.
+ */
 function og_mailinglist_update_6005() {
   $ret = array();
-  
-  $weight = db_result(db_query("SELECT weight FROM {system} WHERE type = 'module' AND name = 'pathauto'"));
+
+  $weight = db_query("SELECT weight FROM {system} WHERE type = :type AND name = :name", array(':type' => : type, ':name' => : name, '' => array(
+      ':type' => : type,
+      ':name' => : name,
+      '' => array(
+        ':type' => 'module',
+        ':name' => 'pathauto',
+      ),
+    )))->fetchField();
   if (!empty($weight)) {
-    db_query("UPDATE {system} SET weight = %d WHERE type = 'module' AND name = 'og_mailinglist'", $weight + 1);
+    db_update('system')
+      ->fields(array(
+      'weight' => $weight + 1,
+    ))
+      ->condition('type', 'module')
+      ->condition('name', 'og_mailinglist')
+      ->execute();
   }
 
-  return $ret;
+  // hook_update_N() no longer returns a $ret array. Instead, return
+  // nothing or a translated string indicating the update ran successfully.
+  // See http://drupal.org/node/224333#update_sql.
+  return t('TODO Add a descriptive string here to show in the UI.') /* t('OG MailingList Update 6005 executed') */;
 }
 
 function add_groups_to_og_mailinglist() {
   if (!module_exists('purl') && !module_exists('spaces_og')) {
-    $results = db_query("SELECT nid, title FROM {node} WHERE type = 'group'");
-   
+    $results = db_query("SELECT nid, title FROM {node} WHERE type = :type", array(':type' => : type, '' => array(
+        ':type' => : type,
+        '' => array(':type' => 'group'),
+      )));
+
     $groups = array();
-   
+
     while ($data = db_fetch_array($results)) {
       $groups[$data['nid']] = $data['title'];
     }
-   
+
     foreach ($groups as $nid => $title) {
       $title = string_to_machine_readable($title);
-      db_query("INSERT INTO {og_mailinglist}
-               VALUES (%d, '%s')", $nid, $title);
-      
+      db_insert('og_mailinglist')
+        ->fields(array(
+        'nid' => $nid,
+        'title' => $title,
+      ))
+        ->execute();
+
       // Subscribe group members to active threads.
       og_mailinglist_create_subscriptions_for_last_month($nid);
     }
@@ -354,15 +424,22 @@ function add_groups_to_og_mailinglist() {
   else {
     $results = db_query("SELECT id, value
                         FROM {purl}
-                        WHERE provider = 'spaces_og'");
+                        WHERE provider = :provider", array(':provider' => : provider, '' => array(
+        ':provider' => : provider,
+        '' => array(':provider' => 'spaces_og'),
+      )));
     $groups = array();
     while ($data = db_fetch_array($results)) {
       $groups[$data['id']] = $data['value'];
     }
     foreach ($groups as $nid => $title) {
-      db_query("INSERT INTO {og_mailinglist}
-               VALUES (%d, '%s')", $nid, $title);
-      
+      db_insert('og_mailinglist')
+        ->fields(array(
+        'nid' => $nid,
+        'title' => $title,
+      ))
+        ->execute();
+
       // Subscribe group members to active threads.
       og_mailinglist_create_subscriptions_for_last_month($nid);
     }
@@ -375,36 +452,48 @@ function add_groups_to_og_mailinglist() {
  */
 function og_mailinglist_create_subscriptions_for_last_month($gid) {
   module_load_include('inc', 'og_mailinglist', 'og_mailinglist_api');
-  
+
   // Create email subscriptions to group for all group members.
   $results = db_query("SELECT uid
                        FROM {og_uid}
-                       WHERE nid = %d", $gid);
+                       WHERE nid = :nid", array(':nid' => : nid, '' => array(
+      ':nid' => : nid,
+      '' => array(':nid' => $gid),
+    )));
   $uids = array();
   while ($data = db_fetch_array($results)) {
     $uids[] = $data['uid'];
   }
   og_mailinglist_save_group_subscriptions($gid, $uids);
-  
+
   $sql = "SELECT n.nid
           FROM {og_ancestry} o
           JOIN {node} n
           ON o.nid = n.nid
           WHERE o.group_nid = %d
           AND n.created > (unix_timestamp() - 2592000)";
-          
-  $results = db_query($sql, $gid);
-  
+
+  $results = db_query("SELECT n.nid
+          FROM {og_ancestry} o
+          JOIN {node} n
+          ON o.nid = n.nid
+          WHERE o.group_nid = :o.group_nid
+          AND n.created > :n.created - 2592000)", array(':o.group_nid' => : o . group_nid, ':n.created' => : n . created, '' => array(
+      ':o.group_nid' => : o . group_nid,
+      ':n.created' => : n . created,
+      '' => array(':o.group_nid' => $gid ':n.created' =>),
+    )));
+
   while ($data = db_fetch_array($results)) {
     og_mailinglist_save_group_thread_subscriptions($gid, $data['nid']);
   }
 }
 
 function string_to_machine_readable($str) {
-    $str = strtolower($str);
-    $str = str_replace("-", "", $str);
-    $str = preg_replace('/[^a-z0-9]/', "-", $str);
-    $str = str_replace("--", "-", $str);
-    $str = trim($str, " -");
-    return $str;
-  }
+  $str = strtolower($str);
+  $str = str_replace("-", "", $str);
+  $str = preg_replace('/[^a-z0-9]/', "-", $str);
+  $str = str_replace("--", "-", $str);
+  $str = trim($str, " -");
+  return $str;
+}
diff --git a/og_mailinglist.module b/og_mailinglist.module
index bce6e19..3d3af66 100644
--- a/og_mailinglist.module
+++ b/og_mailinglist.module
@@ -20,14 +20,14 @@
 define('OG_MAILINGLIST_BUILD_FULL', 'og_mailinglist full');
 /**
  * @} End of "Node as block build modes".
-*/
+ */
 
-require_once("og_mailinglist_phpmailer.inc");
-require_once('og_mailinglist_api.inc');
+require_once DRUPAL_ROOT . '/' . "og_mailinglist_phpmailer.inc";
+require_once DRUPAL_ROOT . '/' . 'og_mailinglist_api.inc';
 og_mailinglist_phpmailer_load_library();
 
 /**
- * Implementation of hook_menu(). 
+ * Implements hook_menu(). ().
  */
 function og_mailinglist_menu() {
   # Administration
@@ -62,10 +62,10 @@ function og_mailinglist_menu() {
     'access arguments' => array('manage og_mailinglist subscriptions'),
   );
   $items['og_mailinglist'] = array(
-  'page callback' => 'og_mailinglist_post',
-  'access callback' => TRUE,
-  'type' => MENU_CALLBACK,
-  'file' => 'og_mailinglist_transport.inc',
+    'page callback' => 'og_mailinglist_post',
+    'access callback' => TRUE,
+    'type' => MENU_CALLBACK,
+    'file' => 'og_mailinglist_transport.inc',
   );
 
   return $items;
@@ -74,13 +74,26 @@ function og_mailinglist_menu() {
 /*
  * Implementation of hook_perm().
  */
-function og_mailinglist_perm() {
-  return array('manage og_mailinglist subscriptions');
+/**
+ * @todo Please document this function.
+ * @see http://drupal.org/node/1354
+ */
+function og_mailinglist_permission() {
+  return array(
+    'manage og_mailinglist subscriptions' => array(
+      'title' => t('manage og_mailinglist subscriptions'),
+      'description' => t('TODO Add a description for \'manage og_mailinglist subscriptions\''),
+    ),
+  );
 }
 
 /*
  * Implementation of hook_init().
  */
+/**
+ * @todo Please document this function.
+ * @see http://drupal.org/node/1354
+ */
 function og_mailinglist_init() {
   drupal_add_css(drupal_get_path('module', 'og_mailinglist') . "/og_mailinglist.css");
   drupal_add_js(drupal_get_path('module', 'og_mailinglist') . "/og_mailinglist.js");
@@ -89,7 +102,7 @@ function og_mailinglist_init() {
 /**
  * Admin settings form
  */
-function og_mailinglist_admin_settings() {
+function og_mailinglist_admin_settings($form, &$form_state) {
   $form['og_mailinglist_server_string'] = array(
     '#title' => t('Domain name'),
     '#type' => 'textfield',
@@ -114,7 +127,7 @@ function og_mailinglist_admin_settings() {
     '#default_value' => variable_get('og_mailinglist_reply_to_group', '0'),
     '#description' => t('Set an explicit reply-to header. See http://wiki.list.org/pages/viewpage.action?pageId=4030691 for pros and cons on this setting.'),
   );
-  $node_types = node_get_types();
+  $node_types = node_type_get_types();
   $n_types = array();
   foreach ($node_types as $type) {
     $n_types[$type->type] = $type->name;
@@ -138,21 +151,25 @@ function og_mailinglist_admin_settings() {
     '#title' => t('Default group email subscription type'),
     '#type' => 'select',
     '#default_value' => variable_get('og_mailinglist_default_group_subscription_type', 'email'),
-    '#options' => array('email' => 'email', 'no email' => 'no email', 'digest email' => 'digest email'),
+    '#options' => array(
+      'email' => 'email',
+      'no email' => 'no email',
+      'digest email' => 'digest email',
+    ),
     '#description' => t('Choose the default email subscription for users joining a new group. "Email" means the user will receive an email for each new post. "No email" means the user will recieve no emails except for discussion threads they participate in. "Digest" is the same as "no email" except the user will also receive digest emails. (Users can change this later at http://yoursite.com/og_mailinglist/subscriptions)'),
   );
-  
+
   // Save an incoming key by default.
   if ((variable_get('og_mailinglist_incoming_key', '')) == '') {
-    variable_set('og_mailinglist_incoming_key',  md5(rand()));
+    variable_set('og_mailinglist_incoming_key',     md5(rand()));
   }
 
   $form['og_mailinglist_incoming_key'] = array(
-  '#type'          => 'textfield',
-  '#title'         => t('Message validation string'),
-  '#default_value' => variable_get('og_mailinglist_incoming_key', md5(rand())),
-  '#required' => TRUE,
-  '#description' => t('This string will be used to validate incoming messages.  It can be anything, but must be used on both sides of the transfer. For more see the INSTALL.txt for your Mail Transfer Agent.'),
+    '#type' => 'textfield',
+    '#title' => t('Message validation string'),
+    '#default_value' => variable_get('og_mailinglist_incoming_key', md5(rand())),
+    '#required' => TRUE,
+    '#description' => t('This string will be used to validate incoming messages.  It can be anything, but must be used on both sides of the transfer. For more see the INSTALL.txt for your Mail Transfer Agent.'),
   );
   $form['og_mailinglist_test_email_address'] = array(
     '#title' => t('DEBUGGING: Send an email for all events to a user account'),
@@ -160,28 +177,43 @@ function og_mailinglist_admin_settings() {
     '#default_value' => variable_get('og_mailinglist_test_email_address', ''),
     '#description' => t('For testing / monitoring purposes, you can set one user account to receive all emails sent by OG Mailinglist. Enter the User ID of the user who should receive all emails.'),
   );
-  
+
   return system_settings_form($form);
 }
 
-function og_mailinglist_subscriptions_settings_form() {
+/**
+ * @todo Please document this function.
+ * @see http://drupal.org/node/1354
+ */
+function og_mailinglist_subscriptions_settings_form($form, &$form_state) {
   global $user;
-  
+
   $sql = 'SELECT m.nid as gid, m.subscription_type, n.title
           FROM {og_mailinglist_subscription} m, {node} n
           WHERE m.nid = n.nid
           AND m.uid = %d
           ORDER BY n.title';
-  
-  $results = db_query($sql, $user->uid);
-  
+
+  $results = db_query('SELECT m.nid as gid, m.subscription_type, n.title
+          FROM {og_mailinglist_subscription} m, {node} n
+          WHERE m.nid = :m.nid
+          AND m.uid = :m.uid
+          ORDER BY n.title', array(':m.nid' => : m . nid, ':m.uid' => : m . uid, '' => array(
+      ':m.nid' => : m . nid,
+      ':m.uid' => : m . uid,
+      '' => array(
+        ':m.nid' => n . nid,
+        ':m.uid' => $user->uid,
+      ),
+    )));
+
   $subscription_options = array(
     'email' => t('Email'),
     'no email' => t('No email'),
     'digest email' => t('Digest email'),
   );
   $form = array();
-  
+
   while ($data = db_fetch_array($results)) {
     $form[$data['gid']] = array(
       '#type' => 'fieldset',
@@ -200,14 +232,18 @@ function og_mailinglist_subscriptions_settings_form() {
       '#suffix' => "<hr />",
     );
   }
-    $form['submit'] = array(
-      '#type' => 'submit',
-      '#value' => t('Save Settings')
-    );
-  
+  $form['submit'] = array(
+    '#type' => 'submit',
+    '#value' => t('Save Settings'),
+  );
+
   return $form;
 }
 
+/**
+ * @todo Please document this function.
+ * @see http://drupal.org/node/1354
+ */
 function og_mailinglist_subscriptions_settings_form_submit($form, &$form_state) {
   global $user;
   foreach ($form_state['values'] as $gid => $settings) {
@@ -222,7 +258,10 @@ function og_mailinglist_subscriptions_settings_form_submit($form, &$form_state)
       // If they choose to leave the group.
       if ($settings['leave-group']) {
         og_delete_subscription($gid, $user->uid);
-        $group_name = db_result(db_query("SELECT title FROM {node} WHERE nid = %d", $gid));
+        $group_name = db_query("SELECT title FROM {node} WHERE nid = :nid", array(':nid' => : nid, '' => array(
+            ':nid' => : nid,
+            '' => array(':nid' => $gid),
+          )))->fetchField();
         drupal_set_message(t("You are no longer in the <a href='@gid'>@group_name</a> group", array("@gid" => url("node/" . $gid), "@group_name" => $group_name)));
       }
     }
@@ -230,13 +269,17 @@ function og_mailinglist_subscriptions_settings_form_submit($form, &$form_state)
   drupal_set_message("Your group subscriptions were updated.");
 }
 
+/**
+ * @todo Please document this function.
+ * @see http://drupal.org/node/1354
+ */
 function og_mailinglist_unsubscribe_thread($node) {
   global $user;
   $success = og_mailinglist_delete_thread_subscription($node->nid, $user->uid);
-  
+
   if ($success) {
     return "<div class='messages success'>You were successfully unsubscribed from
-    the post <em>" . l($node->title, "node/" . $node->nid) . " </em>&nbsp;&nbsp; 
+    the post <em>" . l($node->title, "node/" . $node->nid) . " </em>&nbsp;&nbsp;
      " . l("Undo", "og_mailinglist/subscribe/" . $node->nid, array("attributes" => array("id" => "og_mailinglist_undo")))
            . "</div>";
   }
@@ -245,12 +288,16 @@ function og_mailinglist_unsubscribe_thread($node) {
   }
 }
 
+/**
+ * @todo Please document this function.
+ * @see http://drupal.org/node/1354
+ */
 function og_mailinglist_subscribe_thread($node) {
   global $user;
   og_mailinglist_save_thread_subscriptions($node->nid, array($user->uid));
-  
+
   return "<div class='messages success'>You were successfully subscribed to
-    the post <em>" . l($node->title, "node/" . $node->nid) . " </em>&nbsp;&nbsp; 
+    the post <em>" . l($node->title, "node/" . $node->nid) . " </em>&nbsp;&nbsp;
      " . l("Undo", "og_mailinglist/unsubscribe/" . $node->nid, array("attributes" => array("id" => "og_mailinglist_undo")))
            . "</div>";
 }
@@ -258,16 +305,23 @@ function og_mailinglist_subscribe_thread($node) {
 /*
  * Implementation of hook_form_alter().
  */
+/**
+ * @todo Please document this function.
+ * @see http://drupal.org/node/1354
+ */
 function og_mailinglist_form_alter(&$form, $form_state, $form_id) {
-  if ($form['#id'] == 'node-form' && (arg(0) .'/'. arg(1) != 'admin/content')) {
+  if ($form['#id'] == 'node-form' && (arg(0) . '/' . arg(1) != 'admin/content')) {
     // Group nodes
     if (og_is_group_type($form['#node']->type)) {
       if (!module_exists('purl') && !module_exists('spaces_og')) {
         $group_email = "";
         if (isset($form['nid']['#value'])) {
-          $group_email = db_result(db_query("SELECT group_email
+          $group_email = db_query("SELECT group_email
                                              FROM {og_mailinglist}
-                                             WHERE nid = %d", $form['nid']['#value']));
+                                             WHERE nid = :nid", array(':nid' => : nid, '' => array(
+              ':nid' => : nid,
+              '' => array(':nid' => $form['nid']['#value']),
+            )))->fetchField();
         }
         // Add our form, compatible with purl's form.
         $form['og_mailinglist'] = array(
@@ -292,7 +346,7 @@ function og_mailinglist_form_alter(&$form, $form_state, $form_id) {
         // Make sure our submit function is second after node_form_submit.
         $first = array_shift($form['buttons']['submit']['#submit']);
         array_unshift($form['buttons']['submit']['#submit'], $first, "og_mailinglist_group_form_submit");
-     }
+      }
     }
   }
 }
@@ -302,11 +356,17 @@ function og_mailinglist_form_alter(&$form, $form_state, $form_id) {
  * email username is valid.
  */
 function og_mailinglist_group_form_validate($element, &$form_state) {
-  $sql = "SELECT group_email FROM {og_mailinglist} WHERE group_email = '%s'";
+  $query = db_query('og_mailinglist')
+    ->fields('group_email')
+    ->condition('group_email' $element['#value']);
+
   if ($form_state['values']['nid']) {
-    $sql .= ' AND nid != ' . $form_state['values']['nid'];
+    $query->addCondition('nid', $form_state['values']['nid'], '!=');
   }
-  if (db_result(db_query($sql, $element['#value']))) {
+
+  $result = $query->execute();
+
+  if ($result->fetchField()) {
     form_error($element, t('Someone has already choosen that group email address. Please choose another.'));
   }
   else if (preg_match('!^[\.a-z0-9_-]+$!', $element['#value'])) {
@@ -320,6 +380,10 @@ function og_mailinglist_group_form_validate($element, &$form_state) {
 /*
  * Submit handler for og_mailinglist_group_form.
  */
+/**
+ * @todo Please document this function.
+ * @see http://drupal.org/node/1354
+ */
 function og_mailinglist_group_form_submit($form, &$form_state) {
   $group_email = "";
   if (isset($form_state['values']['purl']['value'])) {
@@ -330,14 +394,17 @@ function og_mailinglist_group_form_submit($form, &$form_state) {
   }
 
   og_mailinglist_save_group($form_state['nid'], $group_email);
-  
+
 }
 
 /*
  * Implementation of hook_nodeapi().
  */
-function og_mailinglist_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
-  if ($op == "insert" && $node->status) {
+/**
+ * Implements hook_node_insert().
+ */
+function og_mailinglist_node_insert($node) {
+  if (TRUE && $node->status) {
     $group_node = _og_mailinglist_load_group($node);
 
     // If this node isn't part of a group, return.
@@ -354,46 +421,54 @@ function og_mailinglist_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
     // User might not be automatically subscribed to new threads. Subscribe now if they aren't signed up to get emails normally.
     if (og_mailinglist_get_group_subscription_type($group_node->nid, $node->uid) != "email") {
       og_mailinglist_save_thread_subscriptions($node->nid, array($node->uid));
-    }    
+    }
     // Send emails
     og_mailinglist_send_node_email($node);
   }
+}
+
+/**
+ * @todo Please document this function.
+ * @see http://drupal.org/node/1354
+ */
+function og_mailinglist_nodeapi_OLD(&$node, $op, $a3 = NULL, $a4 = NULL) {
+  // TODO Remaining code in this function needs to be moved to the appropriate new hook function.
   // Node is a group
   if (og_is_group_type($node->type)) {
     switch ($op) {
       case 'load':
         // Load the group's email username.
         if (isset($node->nid)) {
-          $ogm_email = db_result(db_query("SELECT group_email
+          $ogm_email = db_query("SELECT group_email
                                        FROM {og_mailinglist}
-                                       WHERE nid = %d", $node->nid));
+                                       WHERE nid = :nid", array(':nid' => : nid, '' => array(
+              ':nid' => : nid,
+              '' => array(':nid' => $node->nid),
+            )))->fetchField();
           $node->ogm_email = $ogm_email;
         }
         break;
       case 'insert':
       case 'update':
       case 'delete':
-// Disabling this for now. Spaces deletes and recreates a group when you switch presets.
-//        og_mailinglist_delete_group($node->nid);
+        // Disabling this for now. Spaces deletes and recreates a group when you switch presets.
+        //        og_mailinglist_delete_group($node->nid);
         break;
     }
   }
 }
 
 /**
- * Implmentation of hook_comment().
+ * Implements hook_comment_publish().
  */
-function og_mailinglist_comment($comment, $op) {
-  // $comment can be an object or an array.
-  $comment = (object)$comment;
-
-  if ($op == 'publish') {
+function og_mailinglist_comment_publish($comment) {
+  if (TRUE) {
     // Check that the node is published.
     $node = node_load($comment->nid);
     $group_node = _og_mailinglist_load_group($node);
     if ($node->status && is_object($group_node)) {
       og_mailinglist_send_comment_email($comment, $node);
-      
+
       // User might not be subscribed to thread. Subscribe them now if not
       // already subscribed.
       if (!og_mailinglist_check_user_subscribed_to_thread($comment->nid, $comment->uid)) {
@@ -404,7 +479,16 @@ function og_mailinglist_comment($comment, $op) {
 }
 
 /**
- * Implementation of hook_og().
+ * Implmentation of hook_comment().
+ */
+function og_mailinglist_comment_OLD($comment, $op) {
+  // TODO Remaining code in this function needs to be moved to the appropriate new hook function.
+  // $comment can be an object or an array.
+  $comment = (object) $comment;
+}
+
+/**
+ * Implements hook_og().
  *
  * Add a og_mailinglist subscription when a user joins a group
  * and delete should they leave.
@@ -414,7 +498,7 @@ function og_mailinglist_og($op, $gid, $uid, $args) {
     case 'user insert':
       og_mailinglist_save_group_subscriptions($gid, array($uid));
       break;
-    
+
     case 'user delete':
       og_mailinglist_delete_group_subscriptions($gid, array($uid));
       break;
@@ -422,21 +506,21 @@ function og_mailinglist_og($op, $gid, $uid, $args) {
 }
 
 /**
- * Implementation of hook_filter().
+ * Implements hook_filter().
  */
-function og_mailinglist_filter($op, $delta = 0, $format = -1, $text = "") {
+function og_mailinglist_filter_XXX($op, $delta = 0, $format = -1, $text = "") {
   switch ($op) {
     case 'list':
       return array(
-        0 => t('Hide quoted text from comments created via email')
+        0 => t('Hide quoted text from comments created via email'),
       );
-    
+
     case 'description':
       return t('Finds quoted text from comments created via email and hides them.');
-      
+
     case 'prepare':
       return $text;
-    
+
     case 'process':
       return _og_mailinglist_build_quotes_toggle($text);
   }
@@ -445,22 +529,22 @@ function og_mailinglist_filter($op, $delta = 0, $format = -1, $text = "") {
 function _og_mailinglist_build_quotes_toggle($text) {
   module_load_include('inc', 'og_mailinglist', 'og_mailinglist_filter');
   $quotes = _og_mailinglist_find_quoted_sections($text);
-  
+
   if (!empty($quotes)) {
-    foreach ($quotes as $quote) {      
-      $replace = '<br /><span class="toggle-quoted-text">- Show quoted text -</span><div class="quoted-text">'. $quote .'</div>';
+    foreach ($quotes as $quote) {
+      $replace = '<br /><span class="toggle-quoted-text">- Show quoted text -</span><div class="quoted-text">' . $quote . '</div>';
       $text = str_replace($quote, $replace, $text);
-      
+
       // Remove email addresses. Regex borrowed from valid_email_adddress().
       $regex = "([a-zA-Z0-9_\-\.\+\^!#\$%&*+\/\=\?\`\|\{\}~\']+@(?:(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.?)+)";
       preg_match_all($regex, $quote, $matches);
 
-      foreach($matches[0] as $email) {
+      foreach ($matches[0] as $email) {
         $text = str_replace($email, "***@***.***", $text);
       }
     }
-  } 
-  
+  }
+
   return $text;
 }
 
@@ -478,12 +562,16 @@ function _og_mailinglist_remove_quotes($text) {
 /*
  * Implementation of hook_cron().
  */
+/**
+ * @todo Please document this function.
+ * @see http://drupal.org/node/1354
+ */
 function og_mailinglist_cron() {
   // On first run, set digest to run today.
   $next_digest_runtime = variable_get('og_mailinglist_digest_runtime',
           mktime(17, date("I"), date("s"), date("n"), date("j")));
 
-  if (time() > $next_digest_runtime) {
+  if (REQUEST_TIME > $next_digest_runtime) {
     module_load_include('inc', 'og_mailinglist', 'og_mailinglist_digest_email');
 
     // Send off digest emails.
@@ -495,7 +583,7 @@ function og_mailinglist_cron() {
 }
 
 /**
- * Implementation of hook_help().
+ * Implements hook_help().
  */
 function og_mailinglist_help($path, $args) {
   switch ($path) {
diff --git a/og_mailinglist_api.inc b/og_mailinglist_api.inc
index 0497e52..7caeafa 100644
--- a/og_mailinglist_api.inc
+++ b/og_mailinglist_api.inc
@@ -3,7 +3,7 @@
 
 /**
  * Saves new thread subscriptions for members of a group.
- * 
+ *
  * @param int $gid Group ID
  * @param int $nid Node ID
  */
@@ -22,28 +22,38 @@ function og_mailinglist_save_group_thread_subscriptions($gid, $nid) {
  * Returns users who are active email subscribers in a group.
  *
  * @param int $gid Group id to query for subscriptions
- * 
+ *
  * @return array of UIDs and email addresses that are subscribed to this group.
  *  Format = key (UID) => value (email address)
  */
 function og_mailinglist_get_group_subscriptions($gid) {
   $result = db_query("SELECT uid
                      FROM {og_mailinglist_subscription}
-                     WHERE nid = %d
-                     AND subscription_type = 'email'", $gid);
-  
+                     WHERE nid = :nid
+                     AND subscription_type = :subscription_type", array(':nid' => : nid, ':subscription_type' => : subscription_type, '' => array(
+      ':nid' => : nid,
+      ':subscription_type' => : subscription_type,
+      '' => array(
+        ':nid' => $gid,
+        ':subscription_type' => 'email',
+      ),
+    )));
+
   $uids = array();
   while ($data = db_fetch_array($result)) {
-    $uids[] = $data['uid'];  
+    $uids[] = $data['uid'];
   }
-  
+
   $emails = array();
   foreach ($uids as $uid) {
-    $emails[$uid] = db_result(db_query("SELECT mail
+    $emails[$uid] = db_query("SELECT mail
                                    FROM {users}
-                                   WHERE uid = %d", $uid));
+                                   WHERE uid = :uid", array(':uid' => : uid, '' => array(
+        ':uid' => : uid,
+        '' => array(':uid' => $uid),
+      )))->fetchField();
   }
-  
+
   return $emails;
 }
 
@@ -51,34 +61,55 @@ function og_mailinglist_get_group_subscriptions($gid) {
  * @return array of UIDs and email addresses that are subscribed to this thread.
  *  Format = key (UID) => value (email address)
  */
+/**
+ * @todo Please document this function.
+ * @see http://drupal.org/node/1354
+ */
 function og_mailinglist_get_thread_subscriptions($nid) {
   $result = db_query("SELECT uid
                      FROM {og_mailinglist_thread}
-                     WHERE nid = %d", $nid);
-  
+                     WHERE nid = :nid", array(':nid' => : nid, '' => array(
+      ':nid' => : nid,
+      '' => array(':nid' => $nid),
+    )));
+
   $uids = array();
   while ($data = db_fetch_array($result)) {
-    $uids[] = $data['uid'];  
+    $uids[] = $data['uid'];
   }
-  
+
   $emails = array();
   foreach ($uids as $uid) {
-    $emails[$uid] = db_result(db_query("SELECT mail
+    $emails[$uid] = db_query("SELECT mail
                                    FROM {users}
-                                   WHERE uid = %d", $uid));
+                                   WHERE uid = :uid", array(':uid' => : uid, '' => array(
+        ':uid' => : uid,
+        '' => array(':uid' => $uid),
+      )))->fetchField();
   }
-  
+
   return $emails;
 }
 
 /*
  * Check if a user is subscribed to a thread.
  */
+/**
+ * @todo Please document this function.
+ * @see http://drupal.org/node/1354
+ */
 function og_mailinglist_check_user_subscribed_to_thread($nid, $uid) {
-  return db_result(db_query("SELECT uid
+  return db_query("SELECT uid
           FROM {og_mailinglist_thread
-          WHERE nid = %d
-          AND uid = %d", $nid, $uid));
+          WHERE nid = :nid
+          AND uid = :uid", array(':nid' => : nid, ':uid' => : uid, '' => array(
+      ':nid' => : nid,
+      ':uid' => : uid,
+      '' => array(
+        ':nid' => $nid,
+        ':uid' => $uid,
+      ),
+    )))->fetchField();
 }
 
 /*
@@ -87,6 +118,10 @@ function og_mailinglist_check_user_subscribed_to_thread($nid, $uid) {
  *
  * @return null.
  */
+/**
+ * @todo Please document this function.
+ * @see http://drupal.org/node/1354
+ */
 function og_mailinglist_save_thread_subscriptions($nid, $uids) {
   static $saved = array();
   foreach ($uids as $uid) {
@@ -97,8 +132,13 @@ function og_mailinglist_save_thread_subscriptions($nid, $uids) {
     $saved[] = $nid . "_" . $uid;
 
     if ($uid != 0) { // Ignore anonymous users.
-      $result = db_query("INSERT INTO {og_mailinglist_thread}
-             VALUES (%d, %d)", $nid, $uid);
+      $result = db_insert('og_mailinglist_save_thread_subscription')
+        ->fields(array(
+        'nid' => $nid,
+        'uid' => $uid,
+      ))
+        ->execute();
+
       if ($result) {
         // Invoke hook
         module_invoke_all('og_mailinglist_save_thread_subscription', $nid, $uid);
@@ -110,31 +150,58 @@ function og_mailinglist_save_thread_subscriptions($nid, $uids) {
 /*
  * @return subscription type for the given group and user.
  */
+/**
+ * @todo Please document this function.
+ * @see http://drupal.org/node/1354
+ */
 function og_mailinglist_get_group_subscription_type($gid, $uid) {
-  return db_result(db_query("SELECT subscription_type
+  return db_query("SELECT subscription_type
                             FROM {og_mailinglist_subscription}
-                            WHERE nid = %d
-                            AND uid = %d", $gid, $uid));
+                            WHERE nid = :nid
+                            AND uid = :uid", array(':nid' => : nid, ':uid' => : uid, '' => array(
+      ':nid' => : nid,
+      ':uid' => : uid,
+      '' => array(
+        ':nid' => $gid,
+        ':uid' => $uid,
+      ),
+    )))->fetchField();
 }
 
 /*
  * Update a user's subscription type for one of their groups.
  */
+/**
+ * @todo Please document this function.
+ * @see http://drupal.org/node/1354
+ */
 function og_mailinglist_update_group_subcription_type($gid, $uid, $subscription_type) {
-  db_query("UPDATE {og_mailinglist_subscription}
-         SET subscription_type = '%s'
-         WHERE uid = %d
-         AND nid = %d", $subscription_type, $uid, $gid);
+  db_update('og_mailinglist_subscription')
+  ->fields(array(
+    'subscription_type' => $subscription_type,
+  ))
+  ->condition('uid', $uid)
+  ->condition('nid', $gid)
+  ->execute();
 }
 
 /*
  * @param int $gid Group id.
  * @param array $uids array of User IDs to add group subscriptions.
  */
+/**
+ * @todo Please document this function.
+ * @see http://drupal.org/node/1354
+ */
 function og_mailinglist_save_group_subscriptions($gid, $uids) {
   foreach ($uids as $uid) {
-    db_query("INSERT INTO {og_mailinglist_subscription}
-             VALUES (%d, %d, '%s')", $gid, $uid, variable_get('og_mailinglist_default_group_subscription_type', 'email'));
+    db_query('og_mailinglist_subscription')
+      ->fields(array(
+      'nid' => $gid,
+      'uid' => $uid,
+      'subscription_type' => variable_get('og_mailinglist_default_group_subscription_type', 'email'),
+    ))
+      ->execute();
   }
 }
 
@@ -142,13 +209,18 @@ function og_mailinglist_save_group_subscriptions($gid, $uids) {
  * @param int $gid Group id.
  * @param array $uids array of User IDs to add group subscriptions.
  */
+/**
+ * @todo Please document this function.
+ * @see http://drupal.org/node/1354
+ */
 function og_mailinglist_delete_group_subscriptions($gid, $uids) {
   foreach ($uids as $uid) {
     // Delete subscription.
-    db_query("DELETE FROM {og_mailinglist_subscription}
-             WHERE nid = %d
-             AND uid = %d", $gid, $uid);
-    
+    db_delete('og_mailinglist_subscription')
+      ->condition('nid', $gid)
+      ->condition('uid', $uid)
+      ->execute();
+
     og_mailinglist_delete_group_threads($gid, $uid);
   }
 }
@@ -156,16 +228,23 @@ function og_mailinglist_delete_group_subscriptions($gid, $uids) {
 /*
  * Adds person to 15 latest threads in a group.
  */
+/**
+ * @todo Please document this function.
+ * @see http://drupal.org/node/1354
+ */
 function og_mailinglist_subscribe_group_threads($gid, $uid) {
   // Select threads created in the past month.
   $results = db_query("SELECT o.nid
                       FROM {og_ancestry} o
                       INNER JOIN {node} n
                       ON n.nid = o.nid
-                      WHERE o.group_nid = %d
+                      WHERE o.group_nid = :o.group_nid
                       ORDER BY created DESC
-                      LIMIT 15", $gid);
-  
+                      LIMIT 15", array(':o.group_nid' => : o . group_nid, '' => array(
+      ':o.group_nid' => : o . group_nid,
+      '' => array(':o.group_nid' => $gid),
+    )));
+
   while ($data = db_fetch_array($results)) {
     og_mailinglist_save_thread_subscriptions($data['nid'], array($uid));
   }
@@ -175,22 +254,12 @@ function og_mailinglist_subscribe_group_threads($gid, $uid) {
  * Unsubscribe a user from all group threads when they leave that group.
  **/
 function og_mailinglist_delete_group_threads($gid, $uid) {
-  // Delete threads.  See http://drupal.org/node/1079620
-  global $db_type;
-  if ($db_type == 'pgsql') {
-    db_query("DELETE FROM {og_mailinglist_thread} AS m
-             USING {og_ancestry} AS o
-             WHERE (o.nid = m.nid)
-             AND m.uid = %d
-             AND o.group_nid = %d", $uid, $gid);
-  }
-  else {
-    db_query("DELETE FROM m
-             USING {og_mailinglist_thread} AS m, {og_ancestry} AS o
-             WHERE (o.nid = m.nid)
-             AND m.uid = %d
-             AND o.group_nid = %d", $uid, $gid);
-  }
+  db_delete('og_mailinglist_thread', 'm')
+    ->using('og_ancestry', 'o')
+    ->condition('o.nid = m.nid')
+    ->condition('m.uid' $uid)
+    ->condition('o.group_nid' $gid)
+    ->execute();
 }
 
 /**
@@ -204,9 +273,10 @@ function og_mailinglist_delete_thread_subscription($nid, $uid) {
   }
   $deleted[] = $nid . "_" . $uid;
 
-  $result = db_query("DELETE FROM {og_mailinglist_thread}
-           WHERE nid = %d
-           AND uid = %d", $nid, $uid);
+  $result = db_delete('og_mailinglist_thread')
+    ->condition('nid', $nid)
+    ->condition('uid', $uid)
+    ->execute();
 
   if ($result) {
     // Invoke hook
@@ -219,14 +289,30 @@ function og_mailinglist_delete_thread_subscription($nid, $uid) {
 /*
  * Log successful sent email.
  */
+/**
+ * @todo Please document this function.
+ * @see http://drupal.org/node/1354
+ */
 function og_mailinglist_log_email_sent($source, $nid, $cid = 0, $message_id = 0, $in_reply_to = 0, $references = 0, $parent_message_id = 0) {
-  return db_query("INSERT INTO {og_mailinglist_source}
-           VALUES (%d, %d, '%s', '%s', '%s', '%s', '%s')", 
-           $nid, $cid, $source, $message_id, $in_reply_to, $references, $parent_message_id);
+  return db_insert('og_mailinglist_source')
+    ->fields(array(
+    'nid' => $nid,
+    'cid' => $cid,
+    'source' => $source,
+    'message_id' => $message_id,
+    'in_reply_to' => $in_reply_to,
+    'references_header' => $references,
+    'parent_message_id' => $parent_message_id,
+  ))
+    ->execute();
 }
 /*
  * @return PHPMailer object.
  */
+/**
+ * @todo Please document this function.
+ * @see http://drupal.org/node/1354
+ */
 function og_mailinglist_create_mailer() {
   og_mailinglist_phpmailer_load_library();
   $mailer = new PHPMailer(TRUE); // The TRUE param means it will throw exceptions on errors, which we need to catch.
@@ -238,13 +324,20 @@ function og_mailinglist_create_mailer() {
 /*
  * Save group information upon group creation and update.
  */
+/**
+ * @todo Please document this function.
+ * @see http://drupal.org/node/1354
+ */
 function og_mailinglist_save_group($nid, $group_email) {
-  $update = db_result(db_query("SELECT nid
+  $update = db_query("SELECT nid
                                 FROM {og_mailinglist}
-                                WHERE nid = %d", $nid));
+                                WHERE nid = :nid", array(':nid' => : nid, '' => array(
+      ':nid' => : nid,
+      '' => array(':nid' => $nid),
+    )))->fetchField();
   $data = array(
-      'nid' => $nid,
-      'group_email' => $group_email,
+    'nid' => $nid,
+    'group_email' => $group_email,
   );
 
   if ($update) {
@@ -258,23 +351,32 @@ function og_mailinglist_save_group($nid, $group_email) {
 /*
  * Delete group information.
  */
+/**
+ * @todo Please document this function.
+ * @see http://drupal.org/node/1354
+ */
 function og_mailinglist_delete_group($nid) {
   // Delete information from og_mailinglist.
-  db_query("DELETE FROM {og_mailinglist}
-           WHERE nid = %d", $nid);
-  
+  db_delete('og_mailinglist')
+    ->condition('nid', $nid)
+    ->execute();
+
   // Delete group subscriptions from og_mailinglist_subscriptions.
-  db_query("DELETE FROM {og_mailinglist_subscription}
-           WHERE nid = %d", $nid);
+  db_delete('og_mailinglist_subscription')
+    ->condition('nid', $nid)
+    ->execute();
 }
 
 function _og_mailinglist_get_thread_parent_messageid($in_reply_to_message_id, $references) {
   if (empty($in_reply_to_message_id)) {
     return;
   }
-  $parent_message_id = db_result(db_query("SELECT parent_message_id
+  $parent_message_id = db_query("SELECT parent_message_id
                               FROM {og_mailinglist_source}
-                              WHERE message_id = '%s'", $in_reply_to_message_id));
+                              WHERE message_id = :message_id", array(':message_id' => : message_id, '' => array(
+      ':message_id' => : message_id,
+      '' => array(':message_id' => $in_reply_to_message_id),
+    )))->fetchField();
 
   if (!empty($parent_message_id)) {
     return $parent_message_id;
@@ -286,28 +388,41 @@ function _og_mailinglist_get_thread_parent_messageid($in_reply_to_message_id, $r
   $refs_array = explode(" ", $refs);
 
   foreach ($refs_array as $reference) {
-    if(!empty($reference)) {
-        $parent_message_id = db_result(db_query("SELECT parent_message_id
+    if (!empty($reference)) {
+      $parent_message_id = db_query("SELECT parent_message_id
                               FROM {og_mailinglist_source}
-                              WHERE message_id = '%s'", $reference));
+                              WHERE message_id = :message_id", array(':message_id' => : message_id, '' => array(
+          ':message_id' => : message_id,
+          '' => array(':message_id' => $reference),
+        )))->fetchField();
 
-        if (!empty($parent_message_id)) {
-          return $parent_message_id;
-        }
+      if (!empty($parent_message_id)) {
+        return $parent_message_id;
+      }
     }
   }
- 
+
 }
 
 function _og_mailinglist_get_nid_from_parent_messageid($message_id) {
-  return db_result(db_query("SELECT nid
+  return db_query("SELECT nid
                               FROM {og_mailinglist_source}
-                              WHERE message_id = '%s'", $message_id));
+                              WHERE message_id = :message_id", array(':message_id' => : message_id, '' => array(
+      ':message_id' => : message_id,
+      '' => array(':message_id' => $message_id),
+    )))->fetchField();
 }
 
 function _og_mailinglist_get_messageid_from_nid($nid) {
-  return db_result(db_query("SELECT parent_message_id
+  return db_query("SELECT parent_message_id
                               FROM {og_mailinglist_source}
-                              WHERE cid = 0
-                              AND nid = %d", $nid));
+                              WHERE cid = :cid
+                              AND nid = :nid", array(':cid' => : cid, ':nid' => : nid, '' => array(
+      ':cid' => : cid,
+      ':nid' => : nid,
+      '' => array(
+        ':cid' => 0,
+        ':nid' => $nid,
+      ),
+    )))->fetchField();
 }
diff --git a/og_mailinglist_digest_email.inc b/og_mailinglist_digest_email.inc
index be16bca..09bd1ca 100644
--- a/og_mailinglist_digest_email.inc
+++ b/og_mailinglist_digest_email.inc
@@ -1,6 +1,6 @@
 <?php
 
-require_once('og_mailinglist_utilities.inc');
+require_once DRUPAL_ROOT . '/' . 'og_mailinglist_utilities.inc';
 
 define("EMAIL_HEADER", 'background-color: #D1DCFF; font-family: helvetica;
        font-size: 160%; border-top: 1px solid #262c40; padding: 2px');
@@ -33,8 +33,34 @@ function _og_mailinglist_send_digest_emails() {
             AND c.timestamp > (unix_timestamp() - %d)
             AND s.subscription_type = "digest email"';
 
-  $groups_with_new_nodes = db_query($new_nodes_sql, DIGEST_TIME_PERIOD);
-  $groups_with_new_comments = db_query($new_comments_sql, DIGEST_TIME_PERIOD);
+  $groups_with_new_nodes = db_query('SELECT DISTINCT s.nid
+            FROM {og_mailinglist_subscription} s
+            JOIN {og_ancestry} o
+            JOIN {node} n
+            WHERE s.nid = :s.nid
+            AND o.nid = :o.nid
+            AND n.created > :n.created - %d)
+            AND s.subscription_type = :s.subscription_type', array(':s.nid' => : s . nid, ':o.nid' => : o . nid, ':n.created' => : n . created, ':s.subscription_type' => : s . subscription_type, '' => array(
+      ':s.nid' => : s . nid,
+      ':o.nid' => : o . nid,
+      ':n.created' => : n . created,
+      ':s.subscription_type' => : s . subscription_type,
+      '' => array(':s.nid' => o . group_nid ':o.nid' => n . nid ':n.created' =>),
+    )));
+  $groups_with_new_comments = db_query('SELECT DISTINCT s.nid
+            FROM {og_mailinglist_subscription} s
+            JOIN {og_ancestry} o
+            JOIN {comments} c
+            WHERE s.nid = :s.nid
+            AND o.nid = :o.nid
+            AND c.timestamp > :c.timestamp - %d)
+            AND s.subscription_type = :s.subscription_type', array(':s.nid' => : s . nid, ':o.nid' => : o . nid, ':c.timestamp' => : c . timestamp, ':s.subscription_type' => : s . subscription_type, '' => array(
+      ':s.nid' => : s . nid,
+      ':o.nid' => : o . nid,
+      ':c.timestamp' => : c . timestamp,
+      ':s.subscription_type' => : s . subscription_type,
+      '' => array(':s.nid' => o . group_nid ':o.nid' => c . nid ':c.timestamp' =>),
+    )));
 
   $digest_groups = array();
   while ($data = db_fetch_array($groups_with_new_comments)) {
@@ -46,7 +72,7 @@ function _og_mailinglist_send_digest_emails() {
 
   //print_r($digest_groups);
   foreach ($digest_groups as $gid) {
-    $group = node_load(array('nid' => $gid));
+    $group = node_load($gid);
     // Get list of new activity -- new nodes and new comments
     $new_nids = 'SELECT o.nid
                   FROM {node} n
@@ -62,18 +88,38 @@ function _og_mailinglist_send_digest_emails() {
                           AND c.timestamp > (unix_timestamp() - %d)
                           AND o.group_nid = %d';
 
-    $nids_with_new_nodes = db_query($new_nids, DIGEST_TIME_PERIOD, $gid);
-    $nids_with_new_comments = db_query($new_comment_nids, DIGEST_TIME_PERIOD, $gid);
+    $nids_with_new_nodes = db_query('SELECT o.nid
+                  FROM {node} n
+                  JOIN {og_ancestry} o
+                  WHERE n.nid = :n.nid
+                  AND n.created > :n.created - %d)
+                  AND o.group_nid = :o.group_nid', array(':n.nid' => : n . nid, ':n.created' => : n . created, ':o.group_nid' => : o . group_nid, '' => array(
+        ':n.nid' => : n . nid,
+        ':n.created' => : n . created,
+        ':o.group_nid' => : o . group_nid,
+        '' => array(':n.nid' => o . nid ':n.created' =>),
+      )));
+    $nids_with_new_comments = db_query('SELECT c.nid, c.cid
+                          FROM {comments} c
+                          JOIN {og_ancestry} o
+                          WHERE c.nid = :c.nid
+                          AND c.timestamp > :c.timestamp - %d)
+                          AND o.group_nid = :o.group_nid', array(':c.nid' => : c . nid, ':c.timestamp' => : c . timestamp, ':o.group_nid' => : o . group_nid, '' => array(
+        ':c.nid' => : c . nid,
+        ':c.timestamp' => : c . timestamp,
+        ':o.group_nid' => : o . group_nid,
+        '' => array(':c.nid' => o . nid ':c.timestamp' =>),
+      )));
 
     $nids = array();
     while ($data = db_fetch_array($nids_with_new_comments)) {
       $nids[$data['nid']]['status'] = "old";
-      $nids[$data['nid']]['node_obj'] = node_load(array("nid" => $data['nid']));
-      $nids[$data['nid']][$data['cid']] = _comment_load($data['cid']);
+      $nids[$data['nid']]['node_obj'] = node_load($data['nid']);
+      $nids[$data['nid']][$data['cid']] = comment_load($data['cid']);
     }
     while ($data = db_fetch_array($nids_with_new_nodes)) {
       $nids[$data['nid']]['status'] = "new";
-      $nids[$data['nid']]['node_obj'] = node_load(array("nid" => $data['nid']));
+      $nids[$data['nid']]['node_obj'] = node_load($data['nid']);
     }
 
 
@@ -84,9 +130,12 @@ function _og_mailinglist_send_digest_emails() {
       $message_count += og_mailinglist_count_new_messages($nid);
     }
 
-    $group_email = db_result(db_query("SELECT group_email
+    $group_email = db_query("SELECT group_email
                                         FROM {og_mailinglist}
-                                        WHERE nid = %d", $gid));
+                                        WHERE nid = :nid", array(':nid' => : nid, '' => array(
+        ':nid' => : nid,
+        '' => array(':nid' => $gid),
+      )))->fetchField();
 
     $subject = "[" . $group->ogm_email . "] Digest for " . $group_email . "@" . variable_get("og_mailinglist_server_string", $_SERVER['SERVER_NAME'])
           . " - " . $message_count . " Messages in " . count($nids) . " Discussions";
@@ -98,14 +147,16 @@ function _og_mailinglist_send_digest_emails() {
     $body .= "<ul>\n";
     foreach ($nids as $nid) {
       $body .= "<li>" . l($nid['node_obj']->title, "",
-              array('fragment' => "digest-" . $nid['node_obj']->nid,
-              'external' => true))
+              array(
+        'fragment' => "digest-" . $nid['node_obj']->nid,
+        'external' => true,
+      ))
               . " (" . og_mailinglist_count_new_messages($nid) . " New)</li>\n";
     }
     $body .= "</ul>\n";
     $body .= "<hr />\n";
 
-    // Add individual posts. 
+    // Add individual posts.
     foreach ($nids as $nid) {
       $body .= '<a name="digest-' . $nid['node_obj']->nid . '"></a>';
       $body .= '<div style="' . DISCUSSION_HEADER . '">';
@@ -139,19 +190,29 @@ function _og_mailinglist_send_digest_emails() {
     // For each person, send out an email.
     $result = db_query("SELECT uid
                        FROM {og_mailinglist_subscription}
-                       WHERE nid = %d
-                       AND subscription_type = \"digest email\"", $gid);
+                       WHERE nid = :nid
+                       AND subscription_type = :subscription_type email\"", array(':nid' => : nid, ':subscription_type' => : subscription_type, '' => array(
+        ':nid' => : nid,
+        ':subscription_type' => : subscription_type,
+        '' => array(':nid' => $gid ':subscription_type' =>),
+      )));
     $uids = array();
     while ($data = db_fetch_array($result)) {
-      $email = db_result(db_query("SELECT mail
+      $email = db_query("SELECT mail
                                   FROM {users}
-                                  WHERE uid = %d", $data['uid']));
+                                  WHERE uid = :uid", array(':uid' => : uid, '' => array(
+          ':uid' => : uid,
+          '' => array(':uid' => $data['uid']),
+        )))->fetchField();
       $uids[$data['uid']] = $email;
     }
 
     // Add a test user if any.
     if ($uid = variable_get('og_mailinglist_test_email_address', '')) {
-      $email = db_result(db_query("SELECT mail FROM {users} WHERE uid = %d", $uid));
+      $email = db_query("SELECT mail FROM {users} WHERE uid = :uid", array(':uid' => : uid, '' => array(
+          ':uid' => : uid,
+          '' => array(':uid' => $uid),
+        )))->fetchField();
       $uids[$uid] = $email;
     }
 
@@ -171,14 +232,18 @@ function _og_mailinglist_send_digest_emails() {
       $mailer->Body = $body;
       $mailer->isHTML(TRUE);
       $mailer->Send();
-      watchdog('og_mailinglist', 'Sent digest email to @email for group @group', 
+      watchdog('og_mailinglist', 'Sent digest email to @email for group @group',
                 array('@email' => $email, '@group' => $group->title), WATCHDOG_INFO);
     }
   }
 }
 
+/**
+ * @todo Please document this function.
+ * @see http://drupal.org/node/1354
+ */
 function og_mailinglist_style_node_message($node) {
-  $user = user_load(array('uid' => $node->uid));
+  $user = user_load($node->uid);
   $body .= "<div style=\"" . MESSAGE_HEADER . "\"><strong>" .
     l((isset($user->realname) ? $user->realname : $user->name), "user/" . $user->uid, array('absolute' => TRUE))
     . "</strong> " . $user->mail . " " .
@@ -188,12 +253,19 @@ function og_mailinglist_style_node_message($node) {
   $node = og_mailinglist_render_node_body($node);
   $body .= og_mailinglist_prepare_web_content($node->body);
   $body .= "<br />\n";
-  
+
   return $body;
 }
 
+/**
+ * @todo Please document this function.
+ * @see http://drupal.org/node/1354
+ */
 function og_mailinglist_style_comment_message($comment) {
-  $user = user_load(array('uid' => $comment->uid));
+  // TODO Convert "user_load" to "user_load_multiple" if "$comment->uid" is other than a uid.
+  // To return a single user object, wrap "user_load_multiple" with "array_shift" or equivalent.
+  // Example: array_shift(user_load_multiple(array(), $comment->uid))
+  $user = user_load($comment->uid);
   $body = "<div style=\"" . MESSAGE_HEADER . "\"><strong>" .
     l((isset($user->realname) ? $user->realname : $user->name), "user/" . $user->uid, array('absolute' => TRUE))
     . "</strong> " . $user->mail . " " .
@@ -203,16 +275,20 @@ function og_mailinglist_style_comment_message($comment) {
   $comment->comment = _og_mailinglist_remove_quotes($comment->comment);
   $body .= og_mailinglist_prepare_web_content($comment->comment);
   $body .= "<br />\n";
-  
+
   return $body;
 }
 
+/**
+ * @todo Please document this function.
+ * @see http://drupal.org/node/1354
+ */
 function og_mailinglist_count_new_messages($message) {
-    $count = 0;
-    if ($message['status'] === "new") {
-      $count++;
-    }
-    $count += count(array_keys($message)) - 2;
-    
-    return $count;
+  $count = 0;
+  if ($message['status'] === "new") {
+    $count++;
+  }
+  $count += count(array_keys($message)) - 2;
+
+  return $count;
 }
diff --git a/og_mailinglist_filter.inc b/og_mailinglist_filter.inc
index 85c0100..50a7106 100644
--- a/og_mailinglist_filter.inc
+++ b/og_mailinglist_filter.inc
@@ -8,10 +8,10 @@
 // of people do that.
 // Making the switch would vastly simplify the code.
 // We could then hold the regex for each email client in an array and just pass
-// that and the text into a function. 
+// that and the text into a function.
 function _og_mailinglist_find_quoted_sections($text) {
   $quotes = array();
-  
+
   // Some email clients are "special". They don't like to place ">" in front of
   // quotes. We need to give them their own special functions.
   $quotes[] = array();
@@ -27,11 +27,11 @@ function _og_mailinglist_find_quoted_sections($text) {
   $quotes[] = _og_mailinglist_filter_unknown_client4b_quotes($text);
   $quotes[] = _og_mailinglist_filter_unknown_client5_quotes($text);
   $quotes[] = _og_mailinglist_filter_quotes($text);
-  
+
   // Identify the longest quoted section of all possible matches and only
   // remove that one.
   $quotes = _og_mailinglist_longest_string($quotes);
-  
+
   return $quotes;
 }
 
@@ -39,14 +39,14 @@ function _og_mailinglist_find_quoted_sections($text) {
  * Identify the longest quoted section as that should contain all the others
  * that are possibly within it.
  */
-function _og_mailinglist_longest_string ($quotes) {
+function _og_mailinglist_longest_string($quotes) {
   $longest = array();
-  foreach($quotes as $quote) {
+  foreach ($quotes as $quote) {
     if (key($longest) < strlen(implode("", $quote))) {
       $longest = array(strlen(implode("", $quote)) => $quote);
     }
   }
-  
+
   return end($longest);
 }
 
@@ -64,19 +64,19 @@ function _og_mailinglist_filter_quotes($text) {
   foreach ($lines as $line) {
     if (preg_match("/On\s\w{3},\s\w{3}\s\d{1,2},\s\d{4}\sat\s\d{1,2}:\d{2}\s[PM|AM]/s", #Gmail
                              $line, $matches)
-      || preg_match("/On\s\w{3}\s\d{1,2},\s\d{4},\sat\s\d{1,2}:\d{2}\s(AM|PM),\s/s", #Apple mail
-                            $line, $matches)    
-      || preg_match("/On\s\w{3}\s\d{2},\s\d{4},\sat\s[0-9:]{4,5}\s(PM|AM),\s[a-zA-Z\s]+wrote:/s", #unknown as of yet
+         || preg_match("/On\s\w{3}\s\d{1,2},\s\d{4},\sat\s\d{1,2}:\d{2}\s(AM|PM),\s/s", #Apple mail
                             $line, $matches)
-      || preg_match("/On\s\d{1,2}\/\d{1,2}\/\d{1,2},\s.+?<[a-zA-Z0-9_\-\.\+\^!#\$%&*+\/\=\?\`\|\{\}~\']+@(?:(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.?)+>\swrote:/s", # Some mobile email client, blackberry maybe?
+         || preg_match("/On\s\w{3}\s\d{2},\s\d{4},\sat\s[0-9:]{4,5}\s(PM|AM),\s[a-zA-Z\s]+wrote:/s", #unknown as of yet
                             $line, $matches)
-      || preg_match("/On\s\w{3,10},\s\w{3}\s\d{1,2},\s\d{4},\s.+?wrote:/s", #unknown as of yet "On Saturday, May 22, 2010, Joe Smith wrote:"
+         || preg_match("/On\s\d{1,2}\/\d{1,2}\/\d{1,2},\s.+?<[a-zA-Z0-9_\-\.\+\^!#\$%&*+\/\=\?\`\|\{\}~\']+@(?:(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.?)+>\swrote:/s", # Some mobile email client, blackberry maybe?
                             $line, $matches)
-      || preg_match("/On.\d{1,2}\/\d{1,2}\/\d{1,2}.\d{1,2}:\d{1,2}\s(PM|AM),.+?wrote:/s", #unknown as of yet "On 5/21/10 8:43 PM, Joe Smith wrote:"
+         || preg_match("/On\s\w{3,10},\s\w{3}\s\d{1,2},\s\d{4},\s.+?wrote:/s", #unknown as of yet "On Saturday, May 22, 2010, Joe Smith wrote:"
                             $line, $matches)
-      && !$in_quote) {
+         || preg_match("/On.\d{1,2}\/\d{1,2}\/\d{1,2}.\d{1,2}:\d{1,2}\s(PM|AM),.+?wrote:/s", #unknown as of yet "On 5/21/10 8:43 PM, Joe Smith wrote:"
+                            $line, $matches)
+         && !$in_quote) {
+
 
-      
       $quotes[$count][] = $line;
       $in_quote = TRUE;
     }
@@ -84,7 +84,7 @@ function _og_mailinglist_filter_quotes($text) {
       // or the previous line ended w/ a "<" Long emails addresses
       // (e.g. <someaddress@gmail.com>) sometimes get truncated
       // leaving the second part of the line on the next line.
-            || substr(trim(array_pop(end($quotes))), -1) === "<" 
+            || substr(trim(array_pop(end($quotes))), -1) === "<"
       // Same situation as above. But here the <someaddress@gmail.com> is
       // brought down to the next line so the < is at the start of the line.
             || substr(trim($line), 0, 1) === "<"
@@ -101,7 +101,7 @@ function _og_mailinglist_filter_quotes($text) {
   foreach ($quotes as $quote) {
     $quotes_imploded[] = implode($quote, "\n");
   }
-  
+
   return $quotes_imploded;
 }
 
@@ -134,7 +134,7 @@ function _og_mailinglist_filter_outlook_quotes($text) {
   }
   else {
     return array();
-  }  
+  }
 }
 
 /**
@@ -148,7 +148,7 @@ function _og_mailinglist_filter_android_gmail_quotes($text) {
   }
   else {
     return array();
-  }  
+  }
 }
 
 /**
@@ -162,7 +162,7 @@ function _og_mailinglist_filter_unknown_client_quotes($text) {
   }
   else {
     return array();
-  }  
+  }
 }
 
 /**
@@ -176,7 +176,7 @@ function _og_mailinglist_filter_unknown_client2_quotes($text) {
   }
   else {
     return array();
-  }  
+  }
 }
 
 /**
@@ -186,7 +186,7 @@ function _og_mailinglist_filter_unknown_client2_quotes($text) {
  * Sent: Monday, April 05, 2010 5:30 PM
  * To: A group
  * Subject: [a-group] SQL Server Express
- * 
+ *
  */
 function _og_mailinglist_filter_unknown_client3_quotes($text) {
   $regex = "/From:\s.*?\[.*?@.*?\].*?Sent:\s\w*?,\s\w*?\s\d{1,2},\s\d{4}\s\d{1,2}:\d{2}\s(PM|AM).*?To:\s.*?Subject:.*/s";
@@ -206,7 +206,7 @@ function _og_mailinglist_filter_unknown_client3_quotes($text) {
  * Sent: Thursday, 23 September 2010 9:55 AM // Diff from above is in date format.
  * To: test-two@lists.somewhere.com
  * Subject: [test-two] Thursday morning: Forum start via email
- * 
+ *
  */
 function _og_mailinglist_filter_unknown_client3a_quotes($text) {
   $regex = "/From:\s.*?\[.*?@.*?\].*?Sent:\s\w*?,\s\d{1,2}\s\w*?\s\d{4}\s\d{1,2}:\d{2}\s(PM|AM).*?To:\s.*?Subject:.*/s";
@@ -224,10 +224,10 @@ function _og_mailinglist_filter_unknown_client3a_quotes($text) {
  *
  * -----Original Message-----
  * From: Someone <someone@me.com>
- * Date: Sat, 10 Apr 2110 12:25:28 
+ * Date: Sat, 10 Apr 2110 12:25:28
  * To: Entrepreneurship<entrepreneurship@island.byu.edu>
- * Subject: Re: [entrepreneurship] Need Tech Guys to Form 
- * 
+ * Subject: Re: [entrepreneurship] Need Tech Guys to Form
+ *
  */
 function _og_mailinglist_filter_unknown_client4_quotes($text) {
   $regex = "/-----Original\sMessage-----.*?From:\s.*?@.*?Date:\s\w{3},\s\d{1,2}\s.*?:.*?:.*?To:.*?@.*?Subject:.*/s";
@@ -248,7 +248,7 @@ function _og_mailinglist_filter_unknown_client4_quotes($text) {
  * Sent: Friday, 24 September 2010 10:54 AM
  * To: test-one@lists.somewhere.com
  * Subject: Re: [test-one] Test to Group 1 From Email
- * 
+ *
  */
 function _og_mailinglist_filter_unknown_client4a_quotes($text) {
   $regex = "/-----Original\sMessage-----.*?From:\s.*?@.*?Sent:\s\w{3,9},\s\d{1,2}\s.*?:.*?:.*?To:.*?@.*?Subject:.*/s";
@@ -269,7 +269,7 @@ function _og_mailinglist_filter_unknown_client4a_quotes($text) {
  * To: test-one@lists.somewhere.com
  * Subject: [test-one] Test to Group 1 From Email
  * Date: Fri, 24 Sep 2010 09:36:57 +1000
- * 
+ *
  */
 function _og_mailinglist_filter_unknown_client4b_quotes($text) {
   $regex = "/-----\sOriginal\sMessage\s-----.*?From:\s.*?\<.*?@.*?\>.*?To:\s.*?Subject:\s.*?Date:\s\w*?,\s\d{1,2}\s\w*?\s\d{4}\s\d{1,2}:\d{2}:\d{2}\s.*/s";
@@ -286,7 +286,7 @@ function _og_mailinglist_filter_unknown_client4b_quotes($text) {
  * Filter quotes out of emails from yet another email client.
  *
  * On 15 April 2010 21:57, someone someone@example.com wrote:
- * 
+ *
  */
 function _og_mailinglist_filter_unknown_client5_quotes($text) {
   $regex = "/On\s\d{1,2}\s\w.*?\s\d{4}\s\d{2}:\d{2},\s.*?@.*?\s.*?wrote:.*/s";
diff --git a/og_mailinglist_phpmailer.inc b/og_mailinglist_phpmailer.inc
index 276bdb1..51221ce 100644
--- a/og_mailinglist_phpmailer.inc
+++ b/og_mailinglist_phpmailer.inc
@@ -1,62 +1,75 @@
 <?php
 // $Id$
 
-require_once('og_mailinglist_utilities.inc');
-require_once('og_mailinglist_api.inc');
+require_once DRUPAL_ROOT . '/' . 'og_mailinglist_utilities.inc';
+require_once DRUPAL_ROOT . '/' . 'og_mailinglist_api.inc';
 
+/**
+ * @todo Please document this function.
+ * @see http://drupal.org/node/1354
+ */
 function og_mailinglist_send_comment_email($comment, $node) {
   // Check if comment arrived via email so already sent.
   if (_og_mailinglist_email_already_sent($comment->nid, $comment->cid)) {
     return;
   }
-  
+
   $group_node = _og_mailinglist_load_group($node);
 
   $mailer = og_mailinglist_create_mailer();
-  
+
   // Add custom headers.
   $parent_message_id = _og_mailinglist_get_messageid_from_nid($node->nid);
   // If the comment is in reply to another comment, set the in-reply-to header
   // to that comment's message-id, else to the parent post's message-id.
-  $comment_pid = db_result(db_query("SELECT pid 
+  $comment_pid = db_query("SELECT pid
                                       FROM {comments}
-                                      WHERE cid = %d", $comment->cid));
+                                      WHERE cid = :cid", array(':cid' => : cid, '' => array(
+      ':cid' => : cid,
+      '' => array(':cid' => $comment->cid),
+    )))->fetchField();
   if ($comment_pid != 0) {
-    $in_reply_to = db_result(db_query("SELECT message_id
+    $in_reply_to = db_query("SELECT message_id
                                         FROM {og_mailinglist_source}
-                                        WHERE cid = %d", $comment_pid));
-    $references = db_result(db_query("SELECT references_header
+                                        WHERE cid = :cid", array(':cid' => : cid, '' => array(
+        ':cid' => : cid,
+        '' => array(':cid' => $comment_pid),
+      )))->fetchField();
+    $references = db_query("SELECT references_header
                                       FROM {og_mailinglist_source}
-                                      WHERE cid = %d", $comment_pid)) . " " . $in_reply_to;
+                                      WHERE cid = :cid", array(':cid' => : cid, '' => array(
+        ':cid' => : cid,
+        '' => array(':cid' => $comment_pid),
+      )))->fetchField() . " " . $in_reply_to;
   }
   else {
     $in_reply_to = $parent_message_id;
     $references = $parent_message_id; // TODO, this should really also reference each message-id that came before it in order. Easy enough to do w/ a query.
   }
-  
+
   $mailer = og_mailinglist_add_web_headers($mailer, $node, $comment, $in_reply_to, $references);
-  
+
   // Decorate subject.
   $mailer->Subject = "Re: [" . $group_node->ogm_email . "] " . $node->title;
 
   // Decorate body.
   $body = og_mailinglist_prepare_web_content($comment->comment);
   $body = og_mailinglist_build_web_footer($node, $body);
-  
+
   $mailer->Body = $body;
   $mailer->isHTML = TRUE;
   $mailer->AltBody = drupal_html_to_text($body);
 
   //// Add attachments if any.
-  //foreach ($email['attachments'] as $info) { 
+  //foreach ($email['attachments'] as $info) {
   //  $mailer->AddStringAttachment($info['data'], $info['filename']);
   //}
-  
+
   $mailer = _og_mailinglist_add_addresses($mailer, $node, FALSE,
                                  $comment);
-  
+
   $success = $mailer->Send();
-  
+
   if ($success) {
     og_mailinglist_log_email_sent('web', $node->nid, $comment->cid, $mailer->MessageID, $in_reply_to, $references, $parent_message_id);
   }
@@ -64,36 +77,40 @@ function og_mailinglist_send_comment_email($comment, $node) {
     watchdog('og_mailinglist', "OG_Mailinglist couldn't send a new node email.", NULL,
              WATCHDOG_ERROR);
   }
-  
+
   return;
 }
 
+/**
+ * @todo Please document this function.
+ * @see http://drupal.org/node/1354
+ */
 function og_mailinglist_send_node_email($node) {
   // Check if node arrived via email so already sent.
   if (_og_mailinglist_email_already_sent($node->nid)) {
     return;
   }
-  
+
   $group_node = _og_mailinglist_load_group($node);
-  
 
-  
+
+
   // If not a group post, return. We only send out emails for group posts.
   if (empty($group_node)) {
     return;
   }
-  
+
   $mailer = og_mailinglist_create_mailer();
-  
+
   // Add custom headers.
   $mailer = og_mailinglist_add_web_headers($mailer, $node);
 
   // Decorate subject.
   $subject = "[" . $group_node->ogm_email . "] " . $node->title;
-  
+
   // Prepare node body for viewing.
   $node = og_mailinglist_render_node_body($node);
-  
+
   // Decorate body.
   $body = og_mailinglist_prepare_web_content($node->body);
   $body = og_mailinglist_build_web_footer($node, $body, 0, TRUE);
@@ -115,8 +132,8 @@ function og_mailinglist_send_node_email($node) {
   $mailer->Subject = $subject;
   $mailer->Body = $body;
   $mailer->isHTML = TRUE;
-  $mailer->AltBody = drupal_html_to_text($body); 
-  
+  $mailer->AltBody = drupal_html_to_text($body);
+
   // Add attachments if any.
   if (isset($node->files)) {
     foreach ($node->files as $file) {
@@ -128,9 +145,9 @@ function og_mailinglist_send_node_email($node) {
 
 
   $mailer = _og_mailinglist_add_addresses($mailer, $node, TRUE);
-  
+
   $success = $mailer->Send();
-  
+
   if ($success) {
     og_mailinglist_log_email_sent('web', $node->nid, 0, $mailer->MessageID, 0, 0, $mailer->MessageID);
   }
@@ -153,8 +170,12 @@ function og_mailinglist_send_node_email($node) {
  * @return
  *  Node with rendered body.
  */
+/**
+ * @todo Please document this function.
+ * @see http://drupal.org/node/1354
+ */
 function og_mailinglist_render_node_body($node) {
-  $node = (object)$node;
+  $node = (object) $node;
   $node->build_mode = OG_MAILINGLIST_BUILD_FULL;
   $node = node_build_content($node, FALSE, TRUE);
 
@@ -165,11 +186,15 @@ function og_mailinglist_render_node_body($node) {
   unset($node->teaser);
 
   // Allow modules to modify the fully-built node.
-  node_invoke_nodeapi($node, 'alter');
-  
+  module_invoke_all('node_build_alter', $node);
+
   return $node;
 }
 
+/**
+ * @todo Please document this function.
+ * @see http://drupal.org/node/1354
+ */
 function og_mailinglist_add_web_headers($mailer, $node, $comment = 0, $in_reply_to = 0, $references = 0) {
   $group_node = _og_mailinglist_load_group($node);
   global $base_url;
@@ -212,10 +237,10 @@ function _og_mailinglist_add_addresses($mailer, $node, $new_node = FALSE,
   $subscribers = _og_mailinglist_get_subscribers($node, $new_node);
 
   if (!empty($comment)) {
-    $author = user_load(array('uid' => $comment->uid));
+    $author = user_load($comment->uid);
   }
   else {
-    $author = user_load(array('uid' => $node->uid));
+    $author = user_load($node->uid);
   }
 
   if (isset($author->realname)) {
@@ -239,10 +264,12 @@ function _og_mailinglist_add_addresses($mailer, $node, $new_node = FALSE,
     foreach ($subscribers as $subscriber) {
       $mailer->AddBCC($subscriber);
     }
-  } catch (phpmailerException $e) {
-       watchdog('og_mailinglist', t('PHPMailer error: !error', array('!error' => $e->errorMessage())), NULL, WATCHDOG_ERROR);
-  } catch (Exception $e) {
-       watchdog('og_mailinglist', $e->getMessage(), NULL, WATCHDOG_ERROR);
+  }
+  catch (phpmailerException $e) {
+    watchdog('og_mailinglist', t('PHPMailer error: !error', array('!error' => $e->errorMessage())), NULL, WATCHDOG_ERROR);
+  }
+  catch (Exception $e) {
+    watchdog('og_mailinglist', $e->getMessage(), NULL, WATCHDOG_ERROR);
   }
 
   return $mailer;
diff --git a/og_mailinglist_transport.inc b/og_mailinglist_transport.inc
index 9e2958e..0ead538 100755
--- a/og_mailinglist_transport.inc
+++ b/og_mailinglist_transport.inc
@@ -1,8 +1,8 @@
 <?php
 
 // TODO rewrite header info here.
-require_once('og_mailinglist_utilities.inc');
-require_once('og_mailinglist_api.inc');
+require_once DRUPAL_ROOT . '/' . 'og_mailinglist_utilities.inc';
+require_once DRUPAL_ROOT . '/' . 'og_mailinglist_api.inc';
 og_mailinglist_mimeDecode_load_library();
 og_mailinglist_phpmailer_load_library();
 
@@ -33,7 +33,7 @@ function _og_mailinglist_process_email($raw_email, $group_name) {
     $email = array();
 
     $email['original_email_text'] = $raw_email;
-    
+
     // Extract all the needed info from the email into a simple array.
     $email = _og_mailinglist_parse_email($email);
 
@@ -65,31 +65,36 @@ function _og_mailinglist_process_email($raw_email, $group_name) {
 
     // Strip enclosing quotes sometimes added by MS Outlook.
     $group_name = trim($group_name, '"\' ');
-    
+
     // Did we actually get email text back? If not, throw an exception.
     if ($email['mailbody'] == "") {
       throw new Exception(t("Could not parse message body from the text/plain portion of the email."));
     }
-    
+
     // Check the size of the body and kick out if too large (for security).
-    $max_size = variable_get('og_mailinglist_max_message_size', 200);  // 200kb
+    $max_size = variable_get('og_mailinglist_max_message_size', 200); // 200kb
     if (strlen($email['mailbody']) > $max_size * 1024 && $max_size != 0) {
       throw new Exception(t("Discussion items sent via email must be less than !max_size Kb. For security reasons, please post larger messages through the web interface.", array("!max_size" => $max_size)));
     }
-  
+
     // This regex worries me... do *all* email clients place email addresses between <>?
     // Get the user id.
     $mailfrom = $email['headers']['from'];
-    if (preg_match("/<(.*?)>/", $email['headers']['from'], $matches)) { 
+    if (preg_match("/<(.*?)>/", $email['headers']['from'], $matches)) {
       $mailfrom = $matches[1];
     }
-    if (!$email['userid'] = db_result(db_query("SELECT uid
-                                      FROM {users}
-                                      WHERE mail='%s'", $mailfrom))) {
+    if (! $email['userid'] = db_query("SELECT uid
+                                       FROM {users}
+                                       WHERE mail = :mail", array(':mail' => : mail, '' => array(
+        ':mail' => : mail,
+        '' => array(':mail' => $mailfrom),
+      )))->fetchField()) {
+
       // If not posting from their normal email account, let's try their mail alias.
-      $email['userid'] = db_result(db_query("SELECT uid
-                                            FROM {users}
-                                            WHERE data LIKE '%%%s%%'", $mailfrom));
+      $email['userid'] = db_query('users')
+        ->fields('uid')
+        ->condition('data', '%' . $mailfrom . '%', 'LIKE')
+        ->execute()->fetchField();
     }
     if (!$email['userid']) {
       $exception = t("Could not locate the user account for !mailfrom. For security reasons, please post from the email account you are registered with.", array('!mailfrom' => $mailfrom));
@@ -101,45 +106,64 @@ function _og_mailinglist_process_email($raw_email, $group_name) {
     }
     // Check how many posts have been made by this user (for security).
     if (variable_get('og_mailinglist_max_posts_per_hour', 20) > 0) {
-      $one_hour_ago = time() - (60 * 60);
-      $num_recent_posts = db_result(db_query("SELECT count(*)
+      $one_hour_ago = REQUEST_TIME - (60 * 60);
+      $num_recent_posts = db_query("SELECT count(*)
                                              FROM {node}
-                                             WHERE uid=%d AND
-                                             created > %d",
-                                             $email['userid'], $one_hour_ago));
+                                             WHERE uid = :uid AND
+                                             created > :created", array(':uid' => : uid, ':created' => : created, '' => array(
+          ':uid' => : uid,
+          ':created' => : created,
+          '' => array(
+            ':uid' => $email['userid'],
+            ':created' => $one_hour_ago,
+          ),
+        )))->fetchField();
       if ($num_recent_posts > variable_get('og_mailinglist_max_posts_per_hour', 20)) {
-       throw new Exception(t("You have posted via email too many times in the last hour.  For security reasons, please wait a while or post through the regular web interface."));
+        throw new Exception(t("You have posted via email too many times in the last hour.  For security reasons, please wait a while or post through the regular web interface."));
       }
     }
-    
+
     // Get the group id.
-    $email['groupid'] = db_result(db_query("SELECT nid
+    $email['groupid'] = db_query("SELECT nid
                                            FROM {og_mailinglist}
-                                           WHERE LOWER(group_email)='%s'", $group_name));
-    if (!$email['groupid']) { 
+                                           WHERE LOWER(group_email) = :LOWER(group_email)", array(':LOWER(group_email)' => : LOWER(group_email), '' => array(
+        ':LOWER(group_email)' => : LOWER(group_email),
+        '' => array(':LOWER(group_email)' => $group_name),
+      )))->fetchField();
+    if (!$email['groupid']) {
       throw new Exception(t("Could not locate group named !group_name", array('!group_name' => $group_name)));
     }
-    
+
     // Check the this user is a member of this group (for security).
     $results = db_query("SELECT og.nid, n.title
                         FROM {og_uid} og JOIN {node} n
                         JOIN {og} o
-                        WHERE og.uid=%d AND
-                        og.nid=%d AND
-                        og.nid=n.nid AND
-                        o.nid=og.nid", $email['userid'], $email['groupid']);   
-    if (!db_result($results)) { // TODO also check if person is subscribed to this thread -- if they are, let them comment by email.
+                        WHERE og.uid = :og.uid AND
+                        og.nid = :og.nid AND
+                        og.nid = :og.nid AND
+                        o.nid = :o.nid", array(':og.uid' => : og . uid, ':og.nid' => : og . nid, ':og.nid' => : og . nid, ':o.nid' => : o . nid, '' => array(
+        ':og.uid' => : og . uid,
+        ':og.nid' => : og . nid,
+        ':og.nid' => : og . nid,
+        ':o.nid' => : o . nid,
+        '' => array(
+          ':og.uid' => $email['userid'],
+          ':og.nid' => $email['groupid'],
+          ':og.nid' => n . nid,
+          ':o.nid' => og . nid,
+        ),
+      )));
+    if (!$results->fetchField()) { // TODO also check if person is subscribed to this thread -- if they are, let them comment by email.
       throw new Exception(t("You (email: !mailfrom, account page: !account_page) are not a member of this group.  Please join the group via the web site before posting.",
                                array('!mailfrom' => $mailfrom, '!account_page' => url("user/" . $email['userid'], array('absolute' => TRUE)))));
     }
-    
-    // See if the email is a comment to an existing node or a new node. 
+
+    // See if the email is a comment to an existing node or a new node.
     // If the email is a comment to a node, we should be able to get the Node ID of the original node.
     $email['nid'] = og_mailinglist_parse_nid($email['text_plain'], $email['structure']->headers);
-  
+
     // Create the new content in Drupal.
     if (!empty($email['nid'])) { // a new comment
-      
       /* Two checks first before creating the comment.
        * There are at least two reasons why an email could have a nid but not be
        * intended as a new comment.
@@ -149,10 +173,13 @@ function _og_mailinglist_process_email($raw_email, $group_name) {
        */
 
       //  Does the detected nid belong to the same group as the email was forwarded to?
-      $nid_groupid = db_result(db_query("SELECT group_nid
+      $nid_groupid = db_query("SELECT group_nid
                                         FROM {og_ancestry}
-                                        WHERE nid = %d", $email['nid']));
-      
+                                        WHERE nid = :nid", array(':nid' => : nid, '' => array(
+          ':nid' => : nid,
+          '' => array(':nid' => $email['nid']),
+        )))->fetchField();
+
       if ($nid_groupid != $email['groupid']) {
         og_mailinglist_save_node($email);
         exit(0); // So we don't save a comment as well
@@ -177,22 +204,23 @@ function _og_mailinglist_process_email($raw_email, $group_name) {
         og_mailinglist_save_node($email);
         exit(0); // So we don't save a comment as well.
       }
-      
+
       // If we got this far, the email is definitely intended as a new comment.
       og_mailinglist_save_comment($email);
-      
+
     }
-    else {  // A new node.
+    else { // A new node.
       og_mailinglist_save_node($email);
     }
-    
+
     // Tell Exim4 we had success!
-    exit(0);  
-  
-  }catch (Exception $e) {
+    exit(0);
+
+  }
+  catch (Exception $e) {
     try {
       // Compose an email back to the sender informing them of the problem.
-      $head = Array();
+      $head = array();
       $head[] = 'From: ' . variable_get("og_mailinglist_noreply_email", t("no-reply@" . variable_get("og_mailinglist_server_string", $_SERVER['SERVER_NAME'])));
       $head[] = 'References: ' . $email['headers']['message-id'];
       $head[] = 'In-Reply-To: ' . $email['headers']['message-id'];
@@ -202,24 +230,25 @@ function _og_mailinglist_process_email($raw_email, $group_name) {
       $msgfrom = $email['headers']['from'];
       $commentedbody = str_replace("\n", "\n> ", $mailbody);
       $body = "An error occurred while processing your submission:
-      
+
        $errormsg
-  
+
   Please correct this error and try again, or contact the system administrator.  Thank you.
-  
+
   On $msgdate, $msgfrom wrote:
   > $commentedbody";
-      
+
       // send it off
       if (!mail($email['headers']['from'], "Error processing message", $body, implode("\n", $head))) {
         throw new Exception("Mail error");
       }
-    
+
       // print error message to log, then quit
       echo t("Error: !message\n", array('!message' => $e->getMessage()));
       exit(0);
-      
-    }catch (Exception $e2) {
+
+    }
+    catch (Exception $e2) {
       // if we get here, we couldn't even send an email back to sender, so just have Exim compose an error message and send back
       echo t("Error: !e2 ::: Embedded Error: !e\n", array('!e2' => $e2->getMessage(), '!e' => $e->getMessage()));
       exit(1);
@@ -227,10 +256,14 @@ function _og_mailinglist_process_email($raw_email, $group_name) {
   }
 }
 
+/**
+ * @todo Please document this function.
+ * @see http://drupal.org/node/1354
+ */
 function og_mailinglist_save_comment($email) {
   $nid = $email['nid'];
-  $email['node'] = $node = node_load(array('nid' => $nid));
-  
+  $email['node'] = $node = node_load($nid);
+
   // Let other modules alter the new comment or delay posting for another time
   // (e.g. a moderation module might want to delay posting for a time).
   drupal_alter('og_mailinglist_new_email_comment', $email);
@@ -249,7 +282,7 @@ function og_mailinglist_save_comment($email) {
   if (!user_access('post comments')) {
     throw new Exception(t("You do not have rights to post comments in the system."));
   }
-  
+
   // check that this post has comments enabled
   if (node_comment_mode($nid) != COMMENT_NODE_READ_WRITE) {
     throw new Exception(t("Comments have been disabled for this post."));
@@ -261,21 +294,23 @@ function og_mailinglist_save_comment($email) {
   $comment = array();
   $comment['uid'] = $email['userid'];
   $comment['nid'] = $nid;
-  
+
   if (preg_match("/re:\s*\[.*?\]\s*(.*)/i", $email['headers']['subject'], $matches)) {
     $comment['subject'] = $matches[1];
-  }elseif (preg_match("/re: +(.*)/i", $email['headers']['subject'], $matches)) {
+  }
+  elseif (preg_match("/re: +(.*)/i", $email['headers']['subject'], $matches)) {
     $comment['subject'] = $matches[1];
-  }else{
+  }
+  else {
     $comment['subject'] = $email['headers']['subject'];
   }
   $comment['comment'] = $mailbody;
-  
+
   // Get the cid that'll be used. Yes, this isn't a very pretty way to do this.
   // If someone else creates a comment between now and when the comment is
   // actually created, two emails will be sent out for this comment.
-  $cid = 1 + db_result(db_query("SELECT cid FROM {comments} ORDER BY cid DESC LIMIT 1"));
-  
+  $cid = 1 + db_query("SELECT cid FROM {comments} ORDER BY cid DESC LIMIT 1")->fetchField();
+
   // Log that comment came from email so og_mailinglist_phpmailer doesn't send an email as well.
   $parent_message_id = _og_mailinglist_get_thread_parent_messageid($email['headers']['in-reply-to'], $email['headers']['references']);
   og_mailinglist_log_email_sent('email', $nid, $cid, $email['headers']['message-id'], $email['headers']['in-reply-to'], $email['headers']['references'], $parent_message_id);
@@ -284,12 +319,12 @@ function og_mailinglist_save_comment($email) {
   drupal_alter('og_mailinglist_save_commment', $comment);
 
   // Save the new comment.
-  $cid = comment_save($comment);  
-  
+  $cid = comment_save($comment);
+
   if (!$cid) {
     throw new Exception(t("An unknown error occurred while saving your comment."));
-  }  
-  
+  }
+
   $comment['cid'] = $cid; // Not sure why this isn't added automatically.
   _og_mailinglist_email_comment_email($email, $node, $comment);
 
@@ -297,10 +332,18 @@ function og_mailinglist_save_comment($email) {
   $group_node = node_load($email['groupid']);
   // Report activity to watchdog.
   watchdog('og_mailinglist', t("Posted comment for @mailfrom to group @group_name for nid=@nid with cid=@cid",
-      array('@mailfrom' => $sender->name, '@group_name' => $group_node->title,
-        '@nid' => $node->nid, '@cid' => $cid)));
-} 
- 
+      array(
+    '@mailfrom' => $sender->name,
+    '@group_name' => $group_node->title,
+    '@nid' => $node->nid,
+    '@cid' => $cid,
+  )));
+}
+
+/**
+ * @todo Please document this function.
+ * @see http://drupal.org/node/1354
+ */
 function og_mailinglist_save_node($email) {
 
   // Let other modules alter the new node or delay posting for another time (e.g. a moderation module might want to delay posting for a time).
@@ -317,27 +360,30 @@ function og_mailinglist_save_node($email) {
   // Get the nid that'll be used. Yes, this isn't a very pretty way to do this.
   // If someone else creates a node between now and when the node is
   // actually created, two emails will be sent out for this node.
-  $nid = 1 + db_result(db_query("SELECT nid FROM {node} ORDER BY nid DESC LIMIT 1"));
-  
+  $nid = 1 + db_query("SELECT nid FROM {node} ORDER BY nid DESC LIMIT 1")->fetchField();
+
   // Log that comment came from email so og_mailinglist_phpmailer doesn't send an email as well.
   og_mailinglist_log_email_sent('email', $nid, $cid, $email['headers']['message-id'], 0, 0, $email['headers']['message-id']);
-  
+
   // Is the group public? If not, we need to set the node as private.
-  $is_private = db_result(db_query("SELECT og_private
+  $is_private = db_query("SELECT og_private
                                    FROM {og}
-                                   WHERE nid = %d", $email['groupid']));
-  
+                                   WHERE nid = :nid", array(':nid' => : nid, '' => array(
+      ':nid' => : nid,
+      '' => array(':nid' => $email['groupid']),
+    )))->fetchField();
+
   // The og_private table stores a 1 if the group is private and 0 if it's public.
   // node_save() expects the opposite so we'll invert the value of $is_private.
   $is_public = TRUE;
   if ($is_private) {
     $is_public = FALSE;
   }
-  
+
   // Create the new node
   $node->title = $email['headers']['subject'];
   $node->uid = $email['userid'];
-  $node->created = time();
+  $node->created = REQUEST_TIME;
   $node->status = 1; // published
   $node->promote = 0;
   $node->sticky = 0;
@@ -347,7 +393,7 @@ function og_mailinglist_save_node($email) {
   $node->og_public = $is_public;
   $node->og_groups[$email['groupid']] = $email['groupid'];
   $node->comment = variable_get("comment_$node_type", COMMENT_NODE_READ_WRITE);
-  
+
   //// Add attachments if any.TODO fix this someday. Best idea -- save mail objects w/ attachments. On cron scoop them up and add them to nodes/comments
   //if (isset($email['attachments'])) {
   //  $nodeattachments = _og_mailinglist_save_attachments_temp_dir($email['attachments']);
@@ -359,7 +405,7 @@ function og_mailinglist_save_node($email) {
   drupal_alter('og_mailinglist_save_node', $node);
 
   node_save($node);
-  
+
   // Send off email.
   _og_mailinglist_email_node_email($email, $node);
 
@@ -367,8 +413,11 @@ function og_mailinglist_save_node($email) {
   $group_node = node_load($email['groupid']);
   // Report activity to watchdog.
   watchdog('og_mailinglist', t("Posted node for @mailfrom to group @group_name with nid=@nid.",
-      array('@mailfrom' => $sender->name, '@group_name' => $group_node->title,
-        '@nid' => $node->nid)));
+      array(
+    '@mailfrom' => $sender->name,
+    '@group_name' => $group_node->title,
+    '@nid' => $node->nid,
+  )));
 }
 
 function _og_mailinglist_email_node_email($email, $node) {
@@ -377,7 +426,7 @@ function _og_mailinglist_email_node_email($email, $node) {
   $footer = _og_mailinglist_build_footer($node);
   $email = _og_mailinglist_add_footer($email, $footer);
   $email['new_email_text'] = _og_mailinglist_encode_email(array($email['structure']));
-  
+
   // Send it off.
   _og_mailinglist_send_raw_email($email['new_email_text']);
 
@@ -393,17 +442,17 @@ function _og_mailinglist_email_comment_email($email, $node, $comment) {
   $footer = _og_mailinglist_build_footer($node);
   $email = _og_mailinglist_add_footer($email, $footer);
   $email['new_email_text'] = _og_mailinglist_encode_email(array($email['structure']));
-  
+
   // Send it off.
   _og_mailinglist_send_raw_email($email['new_email_text']);
 }
 
 function _og_mailinglist_parse_email($email) {
-  $params['include_bodies'] = true; 
-  $params['decode_bodies'] = true; 
-  $params['decode_headers'] = true; 
+  $params['include_bodies'] = true;
+  $params['decode_bodies'] = true;
+  $params['decode_headers'] = true;
   $params['input'] = $email['original_email_text'];
-  
+
   // do the decode
   $email['structure'] = clone $structure = Mail_mimeDecode::decode($params);
 
@@ -416,7 +465,7 @@ function _og_mailinglist_parse_email($email) {
         $subPart = $part->parts;
 
         foreach ($subPart as $j => $subPartPart) {
-          if (isset($subPartPart->disposition) and ($subPartPart->disposition==='attachment')) {
+          if (isset($subPartPart->disposition) and ($subPartPart->disposition === 'attachment')) {
             $email['attachments'][] = _og_mailinglist_parse_attachment($subPartPart);
           }
           elseif ($subPartPart->ctype_secondary == 'plain') {
@@ -428,7 +477,7 @@ function _og_mailinglist_parse_email($email) {
         }
       }
 
-      if (isset($part->disposition) and ($part->disposition==='attachment')) {
+      if (isset($part->disposition) and ($part->disposition === 'attachment')) {
         $email['attachments'][] = _og_mailinglist_parse_attachment($part);
       }
       elseif (($part->ctype_secondary == 'plain') && empty($email['text'])) {
@@ -453,7 +502,8 @@ function _og_mailinglist_parse_email($email) {
     // Try to convert character set to UTF-8.
     if (!empty($structure->ctype_parameters['charset'])) {
       $email['text'] = drupal_convert_to_utf8($structure->body, $structure->ctype_parameters['charset']);
-    } else {
+    }
+    else {
       $email['text'] = $structure->body;
     }
     $email['html'] = check_markup($email['text']);
@@ -467,11 +517,11 @@ function _og_mailinglist_parse_email($email) {
   // TODO figure out how to pull out sane HTML w/o funky css or other oddities.
   $email['mailbody'] = $email['text'];
   $email['isHTML'] = false;
- 
+
   // Save copy of the original mailbody
-  $email['orig_mailbody'] = $email['mailbody']; 
- 
-  return $email;  
+  $email['orig_mailbody'] = $email['mailbody'];
+
+  return $email;
 }
 // TODO fix attachments for filefield
 
@@ -496,8 +546,8 @@ function _og_mailinglist_parse_content($part) {
 
 function _og_mailinglist_save_files(&$node) {
   global $user;
-  $user = user_load(array('uid' => $node->uid));
-  
+  $user = user_load($node->uid);
+
   // If $node->og_mailinglist_attachments is empty or upload not installed just return
   if (!$node->og_mailinglist_attachments || !module_exists('upload')) {
     return;
@@ -509,17 +559,17 @@ function _og_mailinglist_save_files(&$node) {
     //echo "didn't have permissions?\n\n";
     return;
   }
-  
+
   // Convert $node->og_mailinglist_attachments to $node->files ready for upload to use
   foreach ($node->og_mailinglist_attachments as $filekey => $attachment) {
-  
+
     $limits = _upload_file_limits($user);
     $validators = array(
       'file_validate_extensions' => array($limits['extensions']),
       'file_validate_image_resolution' => array($limits['resolution']),
       'file_validate_size' => array($limits['file_size'], $limits['user_size']),
     );
-    
+
     if ($file = _og_mailinglist_save_file($attachment, $validators)) {
       // Create the $node->files elements
       $file->list = variable_get('upload_list_default', 1);
@@ -552,15 +602,15 @@ function _og_mailinglist_save_file($attachment, $validators = array()) {
   // @todo: this should not be here. we need to figure out the right place.
   $extensions = '';
   foreach ($user->roles as $rid => $name) {
-    $extensions .= ' '. variable_get("upload_extensions_$rid",
+    $extensions .= ' ' . variable_get("upload_extensions_$rid",
     variable_get('upload_extensions_default', 'jpg jpeg gif png txt html doc xls pdf ppt pps odt ods odp'));
   }
-  
+
   // Begin building file object.
   $file = new stdClass();
   $file->filename = file_munge_filename(trim(basename($attachment['filename']), '.'), $extensions);
   $file->filepath = $attachment['filepath'];
-  $file->filemime = file_get_mimetype($file->filename);;
+  $file->filemime = file_get_mimetype($file->filename);
 
   // Rename potentially executable files, to help prevent exploits.
   if (preg_match('/\.(php|pl|py|cgi|asp|js)$/i', $file->filename) && (substr($file->filename, -4) != '.txt')) {
@@ -571,12 +621,12 @@ function _og_mailinglist_save_file($attachment, $validators = array()) {
 
   // Create temporary name/path for newly uploaded files.
   //if (!$dest) {
-    $dest = file_destination(file_create_path($file->filename), FILE_EXISTS_RENAME);
+  $dest = file_destination(file_create_path($file->filename), FILE_EXISTS_RENAME);
   //}
   //$file->source = $source;
   $file->destination = $dest;
   $file->filesize = $attachment['filesize'];
-  
+
   // Call the validation functions.
   $errors = array();
   foreach ($validators as $function => $args) {
@@ -603,10 +653,10 @@ function _og_mailinglist_save_file($attachment, $validators = array()) {
 
   // If we made it this far it's safe to record this file in the database.
   $file->uid = $user->uid;
-  $file->status = FILE_STATUS_TEMPORARY;
-  $file->timestamp = time();
+  $file->status = ~FILE_STATUS_PERMANENT;
+  $file->timestamp = REQUEST_TIME;
   drupal_write_record('files', $file);
-  
+
   // Return the results of the save operation
   return $file;
 
@@ -618,7 +668,7 @@ function _og_mailinglist_save_attachments_temp_dir($attachments) {
     // Save the data to temporary file
     $temp_file = tempnam(file_directory_temp(), 'mail');
     $filepath = file_save_data($info['data'], $temp_file);
-  
+
     // Add the item to the attachments array, and sanitise filename
     $node_attachments[] = array(
       'filename' => _og_mailinglist_sanitise_filename($info['filename']),
@@ -628,7 +678,7 @@ function _og_mailinglist_save_attachments_temp_dir($attachments) {
     );
   }
   file_save_data("hello world", file_directory_path() . "/temp");
-  
+
   // Return the attachments
   return $node_attachments;
 
@@ -660,13 +710,13 @@ function _og_mailinglist_create_new_email($email) {
   $structure = _og_mailinglist_rewrite_headers($structure, $email);
   $structure = _og_mailinglist_add_footer($structure, $email);
   $email['new_email_text'] = _og_mailinglist_encode_email(array($structure));
-  
+
   return $email;
 }
 
 // Turn structure back into a plain text email using recursion.
 function _og_mailinglist_encode_email($structure, $boundary = "", $email = "") {
-  foreach($structure as $part) {   
+  foreach ($structure as $part) {
     if (empty($boundary)) {
       $boundary = $part->ctype_parameters['boundary'];
     }
@@ -681,10 +731,10 @@ function _og_mailinglist_encode_email($structure, $boundary = "", $email = "") {
       if ($boundary) {
         $last_line = array_pop(explode("\n", trim($email)));
         if (strcmp(trim($last_line), trim("--" . $boundary)) != 0) {
-          $email .= "--" . $boundary . "\n";  
-        } 
+          $email .= "--" . $boundary . "\n";
+        }
       }
-      
+
       $email .= _og_mailinglist_encode_email_headers($part->headers) . "\n";
       // Encode the body as base64 if necessary
       if ($part->headers['content-transfer-encoding'] == "base64") {
@@ -705,11 +755,11 @@ function _og_mailinglist_encode_email_headers($array) {
     // We remove quoted-printable as content-transfer-encoding
     // because mime_decode decodes that and PHP doesn't have a function
     // AFAIK to reencode the text as quoted-printable.
-    if ($value && $value !== "quoted-printable") { 
-      $header .= capitalize_headers($key, " -") . ": " . $value . "\n";  
+    if ($value && $value !== "quoted-printable") {
+      $header .= capitalize_headers($key, " -") . ": " . $value . "\n";
     }
   }
-  
+
   return $header;
 }
 
@@ -721,12 +771,12 @@ function _og_mailinglist_rewrite_headers($email, $node, $new_node = FALSE, $comm
   $new_headers['mime-version'] = $headers['mime-version'];
   $new_headers['date'] = $headers['date'];
   if ($new_node) {
-    $new_headers['subject'] = "[" . $group_node->ogm_email . "] " . $node->title;  
+    $new_headers['subject'] = "[" . $group_node->ogm_email . "] " . $node->title;
   }
   else {
     $new_headers['subject'] = $headers['subject'];
   }
-  
+
   $new_headers['from'] = $headers['from'];
   $new_headers['to'] = $group_node->ogm_email . "@" . variable_get('og_mailinglist_server_string', $_SERVER['SERVER_NAME']);
   $new_headers['bcc'] =
@@ -734,7 +784,7 @@ function _og_mailinglist_rewrite_headers($email, $node, $new_node = FALSE, $comm
       _og_mailinglist_get_subscribers($node, $new_node));
   $new_headers['content-type'] = $headers['content-type'];
   $new_headers['content-transfer-encoding'] =  $headers['content-transfer-encoding'];
-  
+
   // Add a reply-to header directed to the group if enabled.
   if (variable_get('og_mailinglist_reply_to_group', FALSE)) {
     $new_headers['reply-to'] = $group_node->ogm_email . "@" . variable_get('og_mailinglist_server_string', $_SERVER['SERVER_NAME']);
@@ -746,98 +796,96 @@ function _og_mailinglist_rewrite_headers($email, $node, $new_node = FALSE, $comm
   $new_headers['List-Post'] = "<mailto:" . $group_node->ogm_email . "@" .
                 variable_get('og_mailinglist_server_string', $_SERVER['SERVER_NAME']) . ">";
   $new_headers['List-Archive'] = url("node/" . $group_node->nid, array('absolute' => TRUE));
-  
+
   // Thread-URL header.
   global $base_url;
   $new_headers['X-Thread-Url'] = $base_url . "/node/" . $node->nid;
-  
+
   // Set x-BeenThere header
   $new_headers['X-BeenThere'] = $group_node->ogm_email . "@" .
                 variable_get('og_mailinglist_server_string', $_SERVER['SERVER_NAME']);
 
   // Set Message-Id
   $new_headers['Message-ID'] = $email['headers']['message-id'];
-  
+
   // Set References
   $new_headers['References'] = $email['headers']['references'];
 
   // Set In-Reply-To.
   $new_headers['in-reply-to'] = $email['headers']['in-reply-to'];
-  
+
   $email['structure']->headers = $new_headers;
-  
+
   return $email;
 }
 
 function _og_mailinglist_add_footer($email, $footer) {
   $headers = $email['structure']->headers;
   $structure = $email['structure'];
-  
-  // If message is 7/8bit text/plain and uses us-ascii charecter set, just 
+
+  // If message is 7/8bit text/plain and uses us-ascii charecter set, just
   // append the footer.
   if (preg_match('/^text\/plain/i', $headers['content-type']) &&
       isset($structure->body)) {
-     $structure->body .= "\n" . $footer;
+    $structure->body .= "\n" . $footer;
   }
   // If message is already multipart, just append new part with footer to end
   // /^multipart\/(mixed|related)/i
-  elseif (preg_match('/^multipart\/(mixed|related)/i', $headers['content-type']) 
-            && isset($structure->parts)) {
+  elseif (preg_match('/^multipart\/(mixed|related)/i', $headers['content-type'])
+               && isset($structure->parts)) {
     $structure->parts[] = (object) array(
-    "headers" => array(
-      "content-type" => 'text/plain; charset="us-ascii"',
-      "mime-version" => '1.0',
-      "content-transfer-encoding" => '7bit',
-      "content-disposition" => 'inline',
-    ),  
+      "headers" => array(
+        "content-type" => 'text/plain; charset="us-ascii"',
+        "mime-version" => '1.0',
+        "content-transfer-encoding" => '7bit',
+        "content-disposition" => 'inline',
+      ),
       "ctype_primary" => 'text',
       "ctype_secondary" => 'plain',
       "ctype_parameters" => array(
         "charset" => 'us-ascii',
       ),
-
-    "disposition" => 'inline',
-    "body" => $footer,
+      "disposition" => 'inline',
+      "body" => $footer,
     );
   }
-  else {  
+  else {
     // Else, move existing fields into new MIME entity surrounded by new multipart
     // and append footer field to end.
     $structure->headers['mime-version'] = "1.0";
     $boundary = "Drupal-OG-Mailing-List--" . rand(100000000, 9999999999999);
-    
+
     // Copy email, remove headers from copy, rewrite the content-type, add
     // email copy as parts.
     $content_type = $structure->headers['content-type'];
     $str_clone = clone $structure;
     $str_clone->headers = array('content-type' => $content_type);
-    
+
     $structure->headers['content-type'] = "multipart/mixed; boundary=\"" .
         $boundary . "\"";
     $structure->ctype_primary = "multipart";
     $structure->ctype_secondary = "mixed";
     $structure->ctype_parameters = array('boundary' => $boundary);
     $structure->parts = array($str_clone);
-       $structure->parts[] = (object) array(
+    $structure->parts[] = (object) array(
       "headers" => array(
         "content-type" => 'text/plain; charset="us-ascii"',
         "mime-version" => '1.0',
         "content-transfer-encoding" => '7bit',
         "content-disposition" => 'inline',
-      ),  
-        "ctype_primary" => 'text',
-        "ctype_secondary" => 'plain',
-        "ctype_parameters" => array(
-          "charset" => 'us-ascii',
-        ),
-  
+      ),
+      "ctype_primary" => 'text',
+      "ctype_secondary" => 'plain',
+      "ctype_parameters" => array(
+        "charset" => 'us-ascii',
+      ),
       "disposition" => 'inline',
       "body" => $footer,
-      );
+    );
   }
-  
+
   $email['structure'] = $structure;
-  
+
   return $email;
 }
 
@@ -850,6 +898,10 @@ function _og_mailinglist_send_raw_email($raw_email) {
 /*
  * Try to parse nid from the email.
  */
+/**
+ * @todo Please document this function.
+ * @see http://drupal.org/node/1354
+ */
 function og_mailinglist_parse_nid($email, $headers) {
   $nid = "";
   // Check the in-reply-to header.
@@ -873,11 +925,12 @@ function _og_mailinglist_nid_of_subject($subject) {
   preg_match("/[Rr][Ee]:\s\[.*?\]\s(.+)/s", $subject, $matches);
   $title = $matches[1];
   if ($title) {
-      $nid = db_result(db_query("SELECT nid
-                               FROM {node}
-                               WHERE title like '%%s%'
-                               ORDER BY created desc
-                               LIMIT 1", $title));
+    $nid = db_query('node')
+      ->fields('nid')
+      ->condition('title', "%$title%", 'LIKE')
+      ->orderBy('created', 'desc')
+      ->range(0, 1)
+      ->execute()->fetchField();
   }
   return $nid;
 }
diff --git a/og_mailinglist_utilities.inc b/og_mailinglist_utilities.inc
index faa032d..f839fde 100644
--- a/og_mailinglist_utilities.inc
+++ b/og_mailinglist_utilities.inc
@@ -12,13 +12,16 @@ function _og_mailinglist_get_subscribers($node, $new_node = FALSE) {
   else { // this is a new comment.
     $subscribers = og_mailinglist_get_thread_subscriptions($node->nid);
   }
-  
+
   if (is_numeric(variable_get('og_mailinglist_test_email_address', ''))) {
     $uid = variable_get('og_mailinglist_test_email_address', '');
-    $email = db_result(db_query("SELECT mail FROM {users} WHERE uid = %d", $uid));
+    $email = db_query("SELECT mail FROM {users} WHERE uid = :uid", array(':uid' => : uid, '' => array(
+        ':uid' => : uid,
+        '' => array(':uid' => $uid),
+      )))->fetchField();
     $uids[$uid] = $email;
   }
-  
+
   return $subscribers;
 }
 
@@ -31,26 +34,41 @@ function array_to_comma_delimited_string($array) {
 }
 
 function _og_mailinglist_build_footer($node) {
-    $footer = "--
+  $footer = "--
 Full post: " .  url("node/" . $node->nid, array('absolute' => TRUE))   . "
 Manage my subscriptions: " . url("og_mailinglist/subscriptions", array('absolute' => TRUE)) . "
 Stop emails for this post: " . url("og_mailinglist/unsubscribe/" . $node->nid, array("absolute" => TRUE));
-  
+
   return $footer;
 }
 
+/**
+ * @todo Please document this function.
+ * @see http://drupal.org/node/1354
+ */
 function og_mailinglist_prepare_web_content($text) {
   return check_markup($text);
 }
 
- function _og_mailinglist_email_already_sent($nid, $cid = 0) {
-  return (db_result(db_query("SELECT nid
+function _og_mailinglist_email_already_sent($nid, $cid = 0) {
+  return (db_query("SELECT nid
                FROM {og_mailinglist_source}
-               WHERE nid = %d
-               AND cid = %d", $nid, $cid)));
+               WHERE nid = :nid
+               AND cid = :cid", array(':nid' => : nid, ':cid' => : cid, '' => array(
+      ':nid' => : nid,
+      ':cid' => : cid,
+      '' => array(
+        ':nid' => $nid,
+        ':cid' => $cid,
+      ),
+    )))->fetchField());
 }
 
 
+/**
+ * @todo Please document this function.
+ * @see http://drupal.org/node/1354
+ */
 function og_mailinglist_build_web_footer($node, $body, $cid = 0) {
   $footer = _og_mailinglist_build_footer($node);
   $footer = og_mailinglist_prepare_web_content($footer);
@@ -62,26 +80,26 @@ function og_mailinglist_build_web_footer($node, $body, $cid = 0) {
 
 function dd_log($data, $label = "") {
   $my_file = "/tmp/drupal_log";
-  $fh = fopen($my_file, 'a') or die("can't open file");
+  $fh = fopen($my_file, 'a') or ("can't open file");
   ob_start();
   print_r($data);
   $string_data = ob_get_clean();
-  
+
   if (!empty($label)) {
     $string_data = $label . ": " . $string_data;
   }
-  
+
   fwrite($fh, $string_data . "\n");
   fclose($fh);
 }
 
 function write_string_to_file($data, $name = "lsjdf") {
   $myFile = "/tmp/" . $name;
-  $fh = fopen($myFile, 'w') or die("can't open file");
+  $fh = fopen($myFile, 'w') or ("can't open file");
   ob_start();
   print_r($data);
   $stringData = ob_get_clean();
-    
+
   fwrite($fh, $stringData . "\n");
   fclose($fh);
 }
@@ -92,44 +110,49 @@ function write_string_to_file($data, $name = "lsjdf") {
  * @param array $aSource
  * @return array    copy of source array
  */
-function array_copy ($aSource) {
-    // check if input is really an array
-    if (!is_array($aSource)) {
-        throw new Exception("Input is not an Array");
+function array_copy($aSource) {
+  // check if input is really an array
+  if (!is_array($aSource)) {
+    throw new Exception("Input is not an Array");
+  }
+
+  // initialize return array
+  $aRetAr = array();
+
+  // get array keys
+  $aKeys = array_keys($aSource);
+  // get array values
+  $aVals = array_values($aSource);
+
+  // loop through array and assign keys+values to new return array
+  for ($x = 0; $x < count($aKeys); $x++) {
+    // clone if object
+    if (is_object($aVals[$x])) {
+      $aRetAr[$aKeys[$x]] = clone $aVals[$x];
+      // recursively add array
     }
-    
-    // initialize return array
-    $aRetAr = array();
-    
-    // get array keys
-    $aKeys = array_keys($aSource);
-    // get array values
-    $aVals = array_values($aSource);
-    
-    // loop through array and assign keys+values to new return array
-    for ($x=0;$x<count($aKeys);$x++) {
-        // clone if object
-        if (is_object($aVals[$x])) {
-            $aRetAr[$aKeys[$x]]=clone $aVals[$x];
-        // recursively add array
-        } elseif (is_array($aVals[$x])) {
-            $aRetAr[$aKeys[$x]]=array_copy ($aVals[$x]);
-        // assign just a plain scalar value
-        } else {
-            $aRetAr[$aKeys[$x]]=$aVals[$x];
-        }
+    elseif (is_array($aVals[$x])) {
+      $aRetAr[$aKeys[$x]] = array_copy($aVals[$x]);
+      // assign just a plain scalar value
+    }
+    else {
+      $aRetAr[$aKeys[$x]] = $aVals[$x];
     }
-    
-    return $aRetAr;
+  }
+
+  return $aRetAr;
 }
 
 /*
  * Load the parent group node of a node.
  */
 function _og_mailinglist_load_group($node) {
-  $group_node = node_load(array('nid' => db_result(db_query("SELECT group_nid
+  $group_node = node_load(db_query("SELECT group_nid
                                             FROM {og_ancestry}
-                                            WHERE nid = %d", $node->nid))));
+                                            WHERE nid = :nid", array(':nid' => : nid, '' => array(
+      ':nid' => : nid,
+      '' => array(':nid' => $node->nid),
+    )))->fetchField());
   if (!empty($group_node)) {
     return $group_node;
   }
@@ -146,24 +169,25 @@ function _og_mailinglist_load_group($node) {
  * Function taken from http://www.php.net/manual/en/function.ucwords.php#95325
  */
 function capitalize_headers($words, $charList = null) {
-    // Use ucwords if no delimiters are given
-    if (!isset($charList)) {
-        return ucwords($words);
-    }
+  // Use ucwords if no delimiters are given
+  if (!isset($charList)) {
+    return ucwords($words);
+  }
 
-    // Go through all characters
-    $capitalizeNext = true;
+  // Go through all characters
+  $capitalizeNext = true;
 
-    for ($i = 0, $max = strlen($words); $i < $max; $i++) {
-        if (strpos($charList, $words[$i]) !== false) {
-            $capitalizeNext = true;
-        } else if ($capitalizeNext) {
-            $capitalizeNext = false;
-            $words[$i] = strtoupper($words[$i]);
-        }
+  for ($i = 0, $max = strlen($words); $i < $max; $i++) {
+    if (strpos($charList, $words[$i]) !== false) {
+      $capitalizeNext = true;
+    }
+    else if ($capitalizeNext) {
+      $capitalizeNext = false;
+      $words[$i] = strtoupper($words[$i]);
     }
+  }
 
-    return $words;
+  return $words;
 }
 
 /**
@@ -177,16 +201,16 @@ function og_mailinglist_phpmailer_load_library() {
     // First, try using libraries module.
     if (module_exists('libraries')) {
       // Let's see if PHPMailer is really available from libraries.
-      $phpmailer_library = './'. libraries_get_path('phpmailer') .'/class.phpmailer.php';
+      $phpmailer_library = './' . libraries_get_path('phpmailer') . '/class.phpmailer.php';
       if (file_exists($phpmailer_library)) {
-        include_once $phpmailer_library;
+        include_once DRUPAL_ROOT . '/' . $phpmailer_library;
       }
     }
     // If PHPMailer is not already loaded, then try from module subdirectory.
     if (!class_exists('PHPMailer')) {
-      $phpmailer_library = './'. drupal_get_path('module', 'og_mailinglist') .'/phpmailer/class.phpmailer.php';
+      $phpmailer_library = './' . drupal_get_path('module', 'og_mailinglist') . '/phpmailer/class.phpmailer.php';
       if (file_exists($phpmailer_library)) {
-        include_once $phpmailer_library;
+        include_once DRUPAL_ROOT . '/' . $phpmailer_library;
       }
     }
   }
@@ -194,37 +218,41 @@ function og_mailinglist_phpmailer_load_library() {
   return class_exists('PHPMailer');
 }
 
+/**
+ * @todo Please document this function.
+ * @see http://drupal.org/node/1354
+ */
 function og_mailinglist_mimeDecode_load_library() {
   if (!class_exists('Mail_mimeDecode')) {
     // First we'll try grabbing the file from a few default pear install locations.
     if (file_exists('Mail/mimeDecode.php')) {
-      include_once('Mail/mimeDecode.php');
+      include_once DRUPAL_ROOT . '/' . 'Mail/mimeDecode.php';
     }
     if (!class_exists('Mail_mimeDecode')) {
       if (file_exists('/usr/share/php/Mail/mimeDecode.php')) {
-        include_once('/usr/share/php/Mail/mimeDecode.php');
+        include_once DRUPAL_ROOT . '/' . '/usr/share/php/Mail/mimeDecode.php';
       }
     }
     if (!class_exists('Mail_mimeDecode')) {
       if (file_exists('/usr/share/pear/Mail/mimeDecode.php')) {
-        include_once('/usr/share/pear/Mail/mimeDecode.php');
+        include_once DRUPAL_ROOT . '/' . '/usr/share/pear/Mail/mimeDecode.php';
       }
     }
     // If that didn't work, let's try using the libraries module.
     if (!class_exists('Mail_mimeDecode')) {
       if (module_exists('libraries')) {
         // Let's see if PHPMailer is really available from libraries.
-        $Mail_mimeDecode_library = './'. libraries_get_path('mimeDecode') .'/mimeDecode.php';
+        $Mail_mimeDecode_library = './' . libraries_get_path('mimeDecode') . '/mimeDecode.php';
         if (file_exists($Mail_mimeDecode_library)) {
-          include_once $Mail_mimeDecode_library;
+          include_once DRUPAL_ROOT . '/' . $Mail_mimeDecode_library;
         }
       }
     }
     // If Mail_mimeDecode is still not loaded, then try from module subdirectory.
     if (!class_exists('Mail_mimeDecode')) {
-      $Mail_mimeDecode_library = './'. drupal_get_path('module', 'og_mailinglist') .'/mimeDecode/mimeDecode.php';
+      $Mail_mimeDecode_library = './' . drupal_get_path('module', 'og_mailinglist') . '/mimeDecode/mimeDecode.php';
       if (file_exists($Mail_mimeDecode_library)) {
-        include_once $Mail_mimeDecode_library;
+        include_once DRUPAL_ROOT . '/' . $Mail_mimeDecode_library;
       }
     }
 
