View source
<?php
function simplenews_roles_cron() {
foreach (variable_get('simplenews_roles_tids_rids', array()) as $tid => $rids) {
simplenews_roles_update_subscriptions($tid, $rids);
}
}
function simplenews_roles_form_alter($form_id, &$form) {
if ($form_id == 'simplenews_admin_types_form' && !empty($form['tid']['#value'])) {
$form['#submit']['simplenews_roles_newsletter_submit'] = array();
$role_newsletters = variable_get('simplenews_roles_tids_rids', array());
$form['roles'] = array(
'#type' => 'checkboxes',
'#title' => t('Automatically subscribe users in the following roles to this newsletter'),
'#options' => user_roles(TRUE),
'#default_value' => isset($role_newsletters[$form['tid']['#value']]) ? $role_newsletters[$form['tid']['#value']] : '',
'#description' => t('This newsletter subscription list will consist of only users in the selected roles. This newsletter subscription is automatically syncronized so any users manually added to this list will be removed if they are not in any of the selected roles.'),
'#weight' => 10,
);
}
}
function simplenews_roles_newsletter_submit($form_id, $form_values) {
$role_newsletters = variable_get('simplenews_roles_tids_rids', array());
unset($form_values['roles']['']);
if (count(array_filter($form_values['roles']))) {
$role_newsletters[$form_values['tid']] = $form_values['roles'];
simplenews_roles_update_subscriptions($form_values['tid'], $form_values['roles']);
}
else {
unset($role_newsletters[$form_values['tid']]);
}
variable_set('simplenews_roles_tids_rids', $role_newsletters);
}
function simplenews_roles_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
if ($node->type == 'simplenews') {
switch ($op) {
case 'insert':
case 'update':
$term = simplenews_validate_taxonomy($node->taxonomy);
$tid = is_array($term) ? array_shift(array_values($term)) : 0;
$role_newsletters = variable_get('simplenews_roles_tids_rids', array());
if (isset($role_newsletters[$tid])) {
simplenews_roles_update_subscriptions($tid, $role_newsletters[$tid]);
}
break;
}
}
}
function simplenews_roles_update_subscriptions($tid, $rids = array()) {
if (is_array($rids) && $rids) {
$result = db_query('DELETE FROM {simplenews_snid_tid} WHERE tid = %d', $tid);
if (in_array(DRUPAL_AUTHENTICATED_RID, $rids)) {
$result = db_query('SELECT u.mail FROM {users} u WHERE u.status = 1 AND u.uid != 0');
}
else {
$result = db_query('SELECT u.mail FROM {users} u INNER JOIN {users_roles} r ON u.uid = r.uid WHERE u.status = 1 AND (' . implode(' OR ', array_fill(0, count($rids), 'r.rid = %d')) . ')', $rids);
}
while ($account = db_fetch_object($result)) {
simplenews_subscribe_user($account->mail, $tid, FALSE);
}
watchdog('newsletter', t('Newsletter subscription list was automatically regenerated.'));
}
}