--- tarballs/simplenews/simplenews.module	Fri Feb 17 20:08:38 2006
+++ modules/simplenews/simplenews.module	Sun Feb 19 03:19:31 2006
@@ -26,7 +26,7 @@
 
 /**
 * Valid permissions for this module
-*/ 
+*/
 function simplenews_perm() {
   return array('view links in block', 'create newsletter', 'edit own newsletter', 'administer newsletters', 'send newsletter', 'subscribe to newsletters');
 }
@@ -59,7 +59,7 @@
   if (module_exist('simplenews')) {
     theme('add_style', drupal_get_path('module', 'simplenews').'/simplenews.css');
   }
-  
+
   //process subscriptions submitted through blocks before page content is processed
   $result = db_query("SELECT DISTINCT(delta) FROM {blocks} WHERE module = '%s' AND status = %d", 'simplenews', 1);
   while ($delta = db_fetch_object($result)) {
@@ -69,7 +69,7 @@
       simplenews_process_subscription($tid, $edit['sn_email_'.$tid], $edit['sn_subscribe_'.$tid]);
     }
   }
-  
+
   $items = array();
   if ($may_cache) {
     $items[] = array('path' => 'node/add/simplenews', 'title' => t('newsletter'),
@@ -77,14 +77,14 @@
     $items[] = array('path' => 'admin/newsletter', 'title' => t('newsletters'),
                      'access' => user_access('administer newsletters'),
                      'callback' => 'simplenews_admin');
-                     
+
     $items[] = array('path' => 'admin/newsletter/sent', 'title' => t('sent items'),
                      'access' => user_access('administer newsletters'),
                      'type' => MENU_DEFAULT_LOCAL_TASK, 'weight' => -10);
     $items[] = array('path' => 'admin/newsletter/outbox', 'title' => t('drafts'),
                      'access' => user_access('administer newsletters'),
                      'type' => MENU_LOCAL_TASK, 'weight' => -9);
-                     
+
     $items[] = array('path' => 'admin/newsletter/types', 'title' => t('newsletters'),
                      'access' => user_access('administer newsletters'),
                      'type' => MENU_LOCAL_TASK, 'weight' => -8);
@@ -94,7 +94,7 @@
     $items[] = array('path' => 'admin/newsletter/types/add', 'title' => t('add newsletter'),
                      'access' => user_access('administer newsletters'),
                      'type' => MENU_LOCAL_TASK, 'weight' => -9);
-                     
+
     $items[] = array('path' => 'admin/newsletter/users', 'title' => t('subscriptions'),
                      'access' => user_access('administer newsletters'),
                      'type' => MENU_LOCAL_TASK, 'weight' => -7);
@@ -107,14 +107,17 @@
     $items[] = array('path' => 'admin/newsletter/users/export', 'title' => t('export subscriptions'),
                      'access' => user_access('administer newsletters'),
                      'type' => MENU_LOCAL_TASK, 'weight' => -8);
-                     
+    $items[] = array('path' => 'admin/newsletter/users/roles', 'title' => t('role subscriptions'),
+                     'access' => user_access('administer newsletters'),
+                     'type' => MENU_LOCAL_TASK, 'weight' => -7);
+
     $items[] = array('path' => 'admin/newsletter/settings', 'title' => t('settings'),
                      'access' => user_access('administer newsletters'),
                      'type' => MENU_LOCAL_TASK, 'weight' => -6);
     $items[] = array('path' => 'admin/newsletter/settings/general', 'title' => t('general'),
                      'access' => user_access('administer newsletters'),
                      'type' => MENU_DEFAULT_LOCAL_TASK, 'weight' => -10);
-                     
+
     $items[] = array('path' => 'newsletter/confirm', 'title' => t('confirm newsletter subscriptions'),
                      'access' => user_access('access content'),
                      'callback' => 'simplenews_confirm_subscription',
@@ -161,9 +164,9 @@
     '#required' => TRUE,
     '#description' => t('This will be the body of your newsletter. Available variables are:') . ' %site ' . t('(the name of your website),') . ' %uri ' . t('(a link to your homepage),') . ' %uri_brief ' . t('(homepage link without the http://),') . ' %mymail ' . t('(your e-mail address),') . ' %date ' . t('(today\'s date),') . ' %login_uri ' . t('(link to login page).'),
   );
-  
+
   $form['format'] = filter_form($node->format);
-  
+
   if (!$sel1 = $node->s_format) {
     $sel1 = variable_get('simplenews_format', 'plain');
   }
@@ -392,7 +395,7 @@
   elseif ($op == 'delete' && $type == 'vocabulary' && $object->vid == simplenews_get_vid())  {
     variable_del('simplenews_vid');
   }
-} 
+}
 
 
 /**
@@ -821,7 +824,7 @@
       '#options' => $options,
     );
     $submit = t('Submit');
-  }  
+  }
   else {
     $sn_form .= '<div class="form-item"><label for="edit-sn_email">'.t('E-mail').':</label><br /><small>';
     $sn_form .= truncate_utf8($email, 29, FALSE, TRUE);
@@ -891,7 +894,7 @@
   }
   else {
     $pattern = '@(<a href=)"(.\S+?)"([^>]*>)@ei';
-    $node->body = preg_replace($pattern, "'\\1' . '\"' . _sn_mail_url('\\2') . '\"' . '\\3'", $node->body); 
+    $node->body = preg_replace($pattern, "'\\1' . '\"' . _sn_mail_url('\\2') . '\"' . '\\3'", $node->body);
   }
   $address_default = variable_get('site_mail', ini_get('sendmail_from'));
   $name_default = variable_get('site_name', 'drupal');
@@ -906,6 +909,108 @@
   return $node;
 }
 
+function _sn_unsubscribe_delete($result, $tid) {
+  while ($user = db_fetch_object($result)) {
+    db_query("DELETE FROM {sn_snid_tid} WHERE snid = %d AND tid = %d AND role_subscription = 1", $user->snid, $tid);
+    if (!db_num_rows(db_query('SELECT tid FROM {sn_snid_tid} WHERE snid = %d', $user->snid))) {
+      db_query('DELETE FROM {sn_subscriptions} WHERE snid = %d', $subs->snid);
+    }
+  }
+  drupal_set_message(t('Deleted role from subscriptions.'));
+}
+
+function _sn_unsubscribe_roles($roles_unsubscribed, $tid) {
+  if (in_array(2, $roles_unsubscribed)) {
+    $result = db_query('SELECT DISTINCT(s.snid) FROM {users} u INNER JOIN {sn_subscriptions} s ON u.uid = s.uid');
+    _sn_unsubscribe_delete($result, $tid);
+    return;
+  }
+  else {
+    foreach ($roles_unsubscribed as $role) {
+      $result = db_query('SELECT DISTINCT(s.snid) FROM {users_roles} u INNER JOIN {sn_subscriptions} s ON u.uid = s.uid WHERE u.rid = %d', $role);
+      _sn_unsubscribe_delete($result, $tid);
+    }
+  }
+}
+
+function _sn_subscribe_users($emails, $type, $tid, $tree) {
+  if (!$emails) {
+    return;
+  }
+  $emails = ltrim($emails, ',');
+  $emails = explode(",", $emails);
+   foreach ($emails as $email) {
+    $email = trim($email);
+    if (valid_email_address($email)) {
+      $result = db_query("SELECT snid FROM {sn_subscriptions} WHERE mail = '%s'", $email);
+      if (!db_num_rows($result)) {
+        $query = "SELECT uid FROM {users} WHERE mail = '%s'";
+        if ($result = db_fetch_object(db_query($query, $email))) {
+          $uid = $result->uid;
+        }
+        else {
+          $uid = 0;
+        }
+        if (db_query("INSERT INTO {sn_subscriptions} (mail, uid, a_status) VALUES ('%s', %d, %d)", $email, $uid, 1)) {
+          $result = db_query("SELECT snid FROM {sn_subscriptions} WHERE mail = '%s'", $email);
+          $watchdog = t('User %email added to the database.', array('%email'=>theme('placeholder', $email)));
+          watchdog('newsletter', $watchdog);
+        }
+      }
+      if (db_num_rows($result)) $added[] .= $email;
+      if ($tree) {
+        $snid = db_result($result);
+        if ($type == 'import_subscriptions') {
+          foreach ($tree as $newsletter) {
+            if ($tid['tid_'.$newsletter->tid]) {
+              $newsletter_names[] = $newsletter->name;
+              $snid_tid = db_query('SELECT snid FROM {sn_snid_tid} WHERE snid = %d AND tid = %d', $snid, $newsletter->tid);
+              if (!db_num_rows($snid_tid)) {
+                db_query('INSERT INTO {sn_snid_tid} (snid, tid, role_subscription) VALUES (%d, %d, %d)', $snid, $newsletter->tid, 0);
+              }
+            }
+          }
+        }
+        else {
+          $newsletter = taxonomy_get_term($tid);
+          $newsletter_name = $newsletter->name;
+          $snid_tid = db_query('SELECT snid FROM {sn_snid_tid} WHERE snid = %d AND tid = %d', $snid, $tid);
+          if (!db_num_rows($snid_tid)) {
+            db_query('INSERT INTO {sn_snid_tid} (snid, tid, role_subscription) VALUES (%d, %d, %d)', $snid, $tid, 1);
+          }
+        }
+      }
+    }
+    else {
+      $invalid[] .= $email;
+    }
+  }
+
+  if ($added) {
+    $added = implode(", ", $added);
+    if ($type == 'role_subscriptions') {
+      drupal_set_message(t("The following addresses were added or updated to <strong>$newsletter_name</strong>: %added.", array('%added'=>theme('placeholder', $added))));
+    }
+    elseif ($type == 'import_subscriptions') {
+      drupal_set_message(t("The following addresses were added or updated to <strong>" . explode ($newsletter_names, ', ') . "</strong>: %added.", array('%added'=>theme('placeholder', $added))));
+    }
+  }
+  else {
+    if ($type == 'role_subscriptions') {
+      drupal_set_message(t("No addresses were added to <strong>$newsletter_name.</strong>"));
+    }
+    elseif ($type == 'import_subscriptions') {
+      drupal_set_message(t("No addresses were added to <strong>" . explode ($newsletter_names, ', ') . "</strong>"));
+    }
+  }
+  if ($invalid) {
+    $invalid = implode(", ", $invalid);
+    drupal_set_message(t('The following addresses were invalid: %invalid.', array('%invalid'=>theme('placeholder', $invalid))), 'error');
+  }
+}
+
+
+
 /**
 * Send the newsletter
 */
@@ -924,6 +1029,7 @@
     static $counter = 0;
   }
   $result = db_query(db_rewrite_sql('SELECT n.nid, s.tid, n.created FROM {node} n INNER JOIN {sn_newsletters} s ON n.nid = s.nid WHERE s.s_status = %d ORDER BY n.created ASC'), 1);
+
   while ($nid = db_fetch_object($result)) {
     $term = taxonomy_get_term($nid->tid);
     $node = simplenews_node_prepare($nid->nid, $nid->tid);
@@ -1065,7 +1171,7 @@
     }
     _sn_mail_urls(0, TRUE);
   }
-  
+
   // some basic html to text conversion
   $txt = preg_replace(_sn_define_search(), _sn_define_replace(), $txt);
   $txt = preg_replace("/\n\s+\n/", "\n\n", $txt);
@@ -1165,7 +1271,7 @@
         '/&bull;/i',
         '/&[&;]+;/i'
     );
-    
+
     return $search;
 }
 
@@ -1304,11 +1410,14 @@
         $output .= _simplenews_subscription_manager(FALSE, $snid);
       }
       elseif ($op2 == 'add') {
-        $output .= simplenews_admin_list_add();
+        $output .= simplenews_admin_list_add('import_subscriptions');
       }
       elseif ($op2 == 'export') {
         $output .= simplenews_admin_list_export();
       }
+      elseif ($op2 == 'roles') {
+        $output .= simplenews_admin_list_add('role_subscriptions');
+      }
       else {
         $output .= simplenews_admin_list();
       }
@@ -1372,7 +1481,7 @@
       '#default_value' => $_SESSION['simplenews_drafts_filter'],
     );
     $query = "SELECT n.*, s.s_status FROM {node} n INNER JOIN {sn_newsletters} s ON n.nid = s.nid WHERE s.s_status = %d".$queries[$_SESSION['simplenews_drafts_filter']]." ORDER BY n.created DESC";
-    $count_query = "SELECT COUNT(n.nid) FROM {node} n INNER JOIN {sn_newsletters} s ON n.nid = s.nid WHERE s.s_status = %d".$queries[$_SESSION['simplenews_drafts_filter']];
+    $count_query = "SELECT COUNT(n.nid) FROM {node} n INNER JOIN {sn_newsletters} s ON n.nid = s.nid WHERs_status = %d".$queries[$_SESSION['simplenews_drafts_filter']];
   }
   else {
     list($names, $queries) = array_values(simplenews_set_filter('simplenews_sent_filter'));
@@ -1409,7 +1518,7 @@
   );
   $output = drupal_get_form('simplenews_admin_news', $form);
   $output .= theme('table', $header, $rows);
-  
+
   if ($key_table) {
   $key_header = array(array('data' => t('Table key'), 'colspan' => '2'));
   $key_rows[] = array(theme('simplenews_status', 0, 'sent'), t('Not published/Not sent'));
@@ -1417,7 +1526,7 @@
   $key_rows[] = array(theme('simplenews_status', 1, 'sent'), t('Currently sending by cron'));
   $output .= theme('table', $key_header, $key_rows);
   }
-  
+
   return $output;
 }
 
@@ -1490,90 +1599,122 @@
   return $output;
 }
 
-function simplenews_admin_list_add() {
+function simplenews_admin_list_add($type = 'import_subscriptions') {
   $edit = $_POST['edit'];
   $tree = taxonomy_get_tree(simplenews_get_vid());
 
   if ($_POST['op'] == t('Import')) {
-    if ($edit['emails'] != '') {
-      $emails = explode(",", $edit['emails']);
-       foreach ($emails as $email) {
-        $email = trim($email);
-        if (valid_email_address($email)) {
-          $result = db_query("SELECT snid FROM {sn_subscriptions} WHERE mail = '%s'", $email);
-          if (!db_num_rows($result)) {
-            $query = "SELECT uid FROM {users} WHERE mail = '%s'";
-            if ($result = db_fetch_object(db_query($query, $email))) {
-              $uid = $result->uid;
+    if ($type == 'role_subscriptions') {
+      if ($tree) {
+        foreach ($tree as $newsletter) {
+          $checked_roles = $edit['checked_roles_'.$newsletter->tid];
+          $checked_roles = ($checked_roles ? $checked_roles : array());
+          $roles_subscribed_to_newsletter = db_query('SELECT rid FROM {sn_role_subscriptions} u WHERE tid = %d', $newsletter->tid);
+
+          // Delete roles from subscriptions
+          $roles_unsubscribed = array();
+          $roles_subscribed = array();
+          while ($row = db_fetch_object($roles_subscribed_to_newsletter)) {
+            if (!in_array($row->rid, $checked_roles)) {
+              db_query('DELETE FROM {sn_role_subscriptions} WHERE tid = %d AND rid = %d', $newsletter->tid, $row->rid);
+              $roles_unsubscribed[] = $row->rid;
             }
-            else {
-              $uid = 0;
+            $roles_subscribed[] = $row->rid;
+          }
+
+          // Add roles to subscriptions
+          $roles_to_add = array();
+          $roles_to_add = array_diff($checked_roles, $roles_subscribed);
+          $roles_where = array();
+          foreach ($roles_to_add as $role) {
+            db_query('INSERT INTO {sn_role_subscriptions} (tid, rid) VALUES (%d, %d)', $newsletter->tid, $role);
+          }
+          $result_users = '';
+          if (in_array(2, $checked_roles)) {
+            $result_users = db_query('SELECT u.uid FROM {users} u WHERE u.status != 0');
+      } else {
+            foreach ($checked_roles as $rid) {
+              $roles_where[] = 's.rid = ' . $rid;
             }
-            if (db_query("INSERT INTO {sn_subscriptions} (mail, uid, a_status) VALUES ('%s', %d, %d)", $email, $uid, 1)) {
-              $result = db_query("SELECT snid FROM {sn_subscriptions} WHERE mail = '%s'", $email);
-              $watchdog = t('User %email added to the database.', array('%email'=>theme('placeholder', $email)));
-              watchdog('newsletter', $watchdog);
+            $where = (count($roles_where) > 0 ? ' AND (' . implode(' OR ', $roles_where) . ') ': '');
+            if ($where) {
+          $result_users = db_query('SELECT DISTINCT(s.uid) FROM {users_roles} s INNER JOIN {users} u ON u.uid = s.uid WHERE u.status != 0' . $where);
             }
           }
-          if (db_num_rows($result)) $added[] .= $email;
-          if ($tree) {
-            $snid = db_result($result);
-            foreach ($tree as $newsletter) {
-              if ($edit['tid_'.$newsletter->tid]) {
-                $snid_tid = db_query('SELECT snid FROM {sn_snid_tid} WHERE snid = %d AND tid = %d', $snid, $newsletter->tid);
-                if (!db_num_rows($snid_tid)) {
-                  db_query('INSERT INTO {sn_snid_tid} (snid, tid) VALUES (%d, %d)', $snid, $newsletter->tid);
-                }
-              }
+          while ($uid = db_fetch_object($result_users)) {
+            $account = user_load(array('uid' => $uid->uid, 'status' => 1));
+            if($account->mail) {
+              $emails .= ",$account->mail";
             }
           }
+        _sn_subscribe_users($emails, $type, $newsletter->tid, $tree);
+        if ($roles_unsubscribed) {
+          _sn_unsubscribe_roles($roles_unsubscribed, $newsletter->tid);
         }
-        else {
-          $invalid[] .= $email;
+        unset ($emails);
+
         }
       }
     }
-    if ($added) {
-      $added = implode(", ", $added);
-      drupal_set_message(t('The following addresses were added or updated: %added.', array('%added'=>theme('placeholder', $added))));
-    }
-    else {
-      drupal_set_message(t('No addresses were added.'));
+    if ($type = 'import_subscriptions') {
+      _sn_subscribe_users($edit['emails'], $type, $edit, $tree);
     }
-    if ($invalid) {
-      $invalid = implode(", ", $invalid);
-      drupal_set_message(t('The following addresses were invalid: %invalid.', array('%invalid'=>theme('placeholder', $invalid))), 'error');
+  }
+
+  if ($type == 'import_subscriptions') {
+    $form['emails'] = array(
+      '#type' => 'textarea',
+      '#title' => t('E-mail addresses'),
+      '#cols' => 60,
+      '#rows' => 5,
+      '#description' => t('Supply a comma separated list of e-mail addresses to be added to the list. Spaces between commas and addresses are allowed.'),
+    );
+    $form['sn_subscribe_to'] = array(
+      '#type' => 'fieldset',
+      '#title' => t('Subscribe imported addresses to'),
+      '#collapsible' => FALSE,
+    );
+    if ($tree) {
+      foreach ($tree as $newsletter) {
+        $form['sn_subscribe_to']['tid_'.$newsletter->tid] = array(
+          '#type' => 'checkbox',
+          '#title' => $newsletter->name,
+          '#return_value' => 1,
+        );
+        if ($edit['tid_'.$newsletter->tid]) {
+          $to[] .= $newsletter->name;
+        }
+      }
+      if ($to && $added) {
+        $to = implode(", ", $to);
+        drupal_set_message(t('The addresses were subscribed to the following newsletters: %to.', array('%to'=>theme('placeholder', $to))));
+      }
     }
   }
-  
-  $form['emails'] = array(
-    '#type' => 'textarea',
-    '#title' => t('E-mail addresses'),
-    '#cols' => 60,
-    '#rows' => 5,
-    '#description' => t('Supply a comma separated list of e-mail addresses to be added to the list. Spaces between commas and addresses are allowed.'),
-  );
-  $form['sn_subscribe_to'] = array(
-    '#type' => 'fieldset',
-    '#title' => t('Subscribe imported addresses to'),
-    '#collapsible' => FALSE,
-  );
-  if ($tree) {
+  if ($type == 'role_subscriptions') {
     foreach ($tree as $newsletter) {
-      $form['sn_subscribe_to']['tid_'.$newsletter->tid] = array(
-        '#type' => 'checkbox',
+      $form['roles']['tid_'.$newsletter->tid] = array(
+        '#type' => 'fieldset',
         '#title' => $newsletter->name,
-        '#return_value' => 1,
+        '#collapsible' => TRUE,
+        '#collapsed' => TRUE,
+      );
+      $subscribed_roles = array();
+      $roles = db_query('SELECT rid FROM {sn_role_subscriptions} s WHERE s.tid = %d', $newsletter->tid);
+      while ($role = db_fetch_object($roles)) {
+        $subscribed_roles[] = $role->rid;
+      }
+       $form['roles']['tid_'.$newsletter->tid]['checked_roles_'.$newsletter->tid] = array(
+        '#type' => 'checkboxes',
+        '#title' => t('Role subscriptions'),
+        '#default_value' => $subscribed_roles,
+        '#options' => user_roles(1),
+        '#description' => t('Send this newsletter to users in selected roles.'),
+        '#weight' => 0,
       );
-      if ($edit['tid_'.$newsletter->tid]) {
-        $to[] .= $newsletter->name;
-      }
-    }
-    if ($to && $added) {
-      $to = implode(", ", $to);
-      drupal_set_message(t('The addresses were subscribed to the following newsletters: %to.', array('%to'=>theme('placeholder', $to))));
     }
   }
+
   $form['submit'] = array(
     '#type' => 'submit',
     '#value' => t('Import'),
@@ -1686,8 +1827,8 @@
       variable_set('simplenews_block_r_'.$term->tid, $edit['block_r'.$term->tid] ? 1 : 0);
       variable_set('simplenews_block_i_status_'.$term->tid, $edit['block_i_status'.$term->tid] ? 1 : 0);
       variable_set('simplenews_block_i_'.$term->tid, $edit['block_i'.$term->tid]);
-      variable_set('simplenews_block_f_'.$term->tid, $edit['block_f'.$term->tid] ? 1 : 0);      
-      variable_set('simplenews_hyperlinks_'.$term->tid, $edit['hyperlinks'.$term->tid]);      
+      variable_set('simplenews_block_f_'.$term->tid, $edit['block_f'.$term->tid] ? 1 : 0);
+      variable_set('simplenews_hyperlinks_'.$term->tid, $edit['hyperlinks'.$term->tid]);
       variable_set('simplenews_from_name_'.$term->tid, $edit['from_name'.$term->tid]);
       //valid_email_address() allows empty address, so check this first
       if ($edit['from_address'.$term->tid] == '') {
@@ -1777,7 +1918,7 @@
       '#collapsible' => TRUE,
       '#collapsed' => TRUE,
       '#description' => t('When your newsletter is sent as plain text, these options will determine how the conversion to text is performed.'),
-    );    
+    );
     $options[0] = t('Append hyperlinks as a numbered reference list');
     $options[1] = t('Display hyperlinks inline with the text');
     $form['sn_hyperlinks']['hyperlinks'.$term->tid] = array(
@@ -2154,5 +2295,5 @@
   if ($image = theme('image', 'misc/feed.png', t('Syndicate content'), t('Syndicate content'))) {
     return '<div class="sn-feed-icon"><a href="'. $url .'">'. $image. '</a></div>';
   }
-} 
+}
 
