You are here

mailchimp.module in Mailchimp 6

Mailchimp module.

File

mailchimp.module
View source
<?php

/**
 * @file
 * Mailchimp module.
 */
define('SUBSCRIPTION_SUCCESS', t('Thank you, you have been successfully subscribed.'));
define('SUBSCRIPTION_FAILURE', t('We were unable to subscribe you at this time. Please try again later.'));
define('UNSUBSCRIPTION_SUCCESS', t('Thank you, you have been successfully unsubscribed.'));
define('UNSUBSCRIPTION_FAILURE', t('We were unable to unsubscribe you at this time. Please try again later.'));
function mailchimp_user($op, &$edit, &$account, $category = NULL) {
  switch ($op) {
    case "delete":
      if ($q = _mailchimp_get_api_object()) {
        foreach ((array) $q
          ->lists() as $list) {
          $ret = $ret || _mailchimp_unsubscribe_user($list, $account->mail, TRUE, $q);
          if (!$ret) {
            watchdog('mailchimp', $q->errorMessage, array(), WATCHDOG_ERROR);
          }
        }
        if (!$ret) {
          watchdog('mailchimp', $q->errorMessage, array(), WATCHDOG_ERROR);
        }
      }
      break;
    case "form":
      if (variable_get('mailchimp_user_edit', TRUE) && $category == 'account' && ($q = _mailchimp_get_api_object())) {
        $form = array();
        $list_form = array();
        $lists = _mailchimp_get_available_lists($account, $q);
        foreach ($lists as $list) {
          if (variable_get('mailchimp_list_' . $list['id'] . '_listtype', '') !== 'required') {
            $list_form['chimpmail_list_' . $list['id']] = array(
              '#type' => 'checkbox',
              '#title' => $list["name"],
              '#default_value' => _mailchimp_is_subscribed($list['id'], $account->mail, $q),
              '#description' => variable_get('mailchimp_list_' . $list['id'] . '_description', ''),
            );
          }
        }
        if ($list_form) {
          $form['chimpmail_lists'] = array(
            '#type' => 'fieldset',
            '#title' => t('Newsletter subscriptions'),
            '#weight' => 5,
            '#collapsible' => TRUE,
          );
          $form['chimpmail_lists'] = array_merge($form['chimpmail_lists'], $list_form);
        }
        return $form;
      }
      break;
    case "insert":
    case "update":
      if (!empty($edit) && ($q = _mailchimp_get_api_object())) {
        $lists = _mailchimp_get_available_lists($account, $q);
        foreach ($lists as $list) {
          if (variable_get('mailchimp_list_' . $list['id'] . '_listtype', '') === 'required') {
            if (!variable_get('mailchimp_cron', FALSE)) {
              if ($account->mail !== $edit['mail']) {
                $ret = $q
                  ->listUnsubscribe($list['id'], $account->mail, FALSE, FALSE, FALSE);
              }
              $userinfo = _mailchimp_load_user_list_mergevars($account->uid, $list['id'], $q
                ->listMergeVars($list['id']));
              $userinfo['EMAIL'] = $edit['mail'];
              $ret = _mailchimp_subscribe_user($list, $userinfo, FALSE, $q);
            }
          }
          else {
            $is_subscribed = _mailchimp_is_subscribed($list['id'], $account->mail, $q);
            $ret = TRUE;
            if (variable_get('mailchimp_user_edit', TRUE) && $op == "update" && $category == 'account' || variable_get('mailchimp_user_register', TRUE) && $op == "insert") {

              // subscribe the user if they are not previously subscribed and want to be
              if (!$is_subscribed && @$edit['chimpmail_list_' . $list['id']]) {
                $merge_vars = _mailchimp_load_user_list_mergevars($account->uid, $list['id'], $q
                  ->listMergeVars($list['id']));
                $merge_vars['EMAIL'] = $edit['mail'];
                $ret = _mailchimp_subscribe_user($list, $merge_vars, TRUE, $q);
              }
              else {
                if ($is_subscribed && !@$edit['chimpmail_list_' . $list['id']]) {
                  $ret = _mailchimp_unsubscribe_user($list, $account->mail, TRUE, $q);
                }
                else {
                  if ($is_subscribed && $account->mail !== $edit['mail']) {
                    $merge_vars = _mailchimp_load_user_list_mergevars($account->uid, $list['id'], $q
                      ->listMergeVars($list['id']));
                    $merge_vars['EMAIL'] = $edit['mail'];
                    $ret = _mailchimp_update_user($list, $account->mail, $merge_vars, $q);
                  }
                }
              }
            }
            else {
              if ($is_subscribed) {
                $merge_vars = _mailchimp_load_user_list_mergevars($account->uid, $list['id'], $q
                  ->listMergeVars($list['id']));
                $ret = _mailchimp_update_user($list, $account->mail, $merge_vars, $q);
              }
            }
            if (!$ret) {
              watchdog('mailchimp', $q->errorMessage, array(), WATCHDOG_ERROR);
            }
          }
        }
      }
      break;
  }
}

/**
 * Implementation of hook_form_alter() .
 * Add subscription form to registration page
 */
function mailchimp_form_user_register_alter(&$form, &$form_state) {
  if (variable_get('mailchimp_user_register', TRUE)) {
    $account = new stdClass();
    $account->roles = array(
      2 => "authenticated user",
    );
    $lists = _mailchimp_get_available_lists($account, $q);
    if (!empty($lists)) {
      foreach ($lists as $list) {
        if (variable_get('mailchimp_list_' . $list['id'] . '_listtype', '') !== 'required') {
          $list_form['chimpmail_list_' . $list['id']] = array(
            '#type' => 'checkbox',
            '#title' => $list["name"],
            '#default_value' => variable_get('mailchimp_list_' . $list['id'] . '_listtype', '') == 'optout' ? TRUE : FALSE,
            '#description' => variable_get('mailchimp_list_' . $list['id'] . '_description', ''),
          );
        }
      }
      if ($list_form) {
        $form['chimpmail_lists'] = array(
          '#type' => 'fieldset',
          '#title' => t('Newsletter subscriptions'),
          '#weight' => 5,
          '#collapsible' => TRUE,
        );
        $form['chimpmail_lists'] = array_merge($form['chimpmail_lists'], $list_form);
      }
    }
  }
}

/**
 * Implementation of hook_cron. Resubscribes all users to the required lists if the user has chosen to do so.
 */
function mailchimp_cron() {
  if (variable_get('mailchimp_cron', FALSE) && ($q = _mailchimp_get_api_object())) {
    $result = db_query('SELECT uid FROM {users} where status = %d', 1);
    if ($result) {
      $lists = _mailchimp_get_required_lists($q
        ->lists());
      foreach ($lists as $key => $list) {
        $lists[$key]['batch'] = array();
        $lists[$key]['mergevars'] = $q
          ->listMergeVars($list['id']);
      }
      while ($row = db_fetch_object($result)) {
        $account = user_load(array(
          'uid' => $row->uid,
        ));
        foreach ((array) $lists as $key => $list) {
          foreach ((array) $account->roles as $rid => $info) {
            if (variable_get('mailchimp_list_' . $list['id'] . '_role_' . $rid, 0)) {
              $lists[$key]['batch'][] = _mailchimp_load_user_list_mergevars($row->uid, $list['id'], $lists[$key]['mergevars']);
              break;
            }
          }
        }
      }
      $count = 0;
      foreach ($lists as $key => $list) {
        if (count($lists[$key]['batch'])) {
          $ret = $q
            ->listBatchSubscribe($list['id'], $lists[$key]['batch'], FALSE, TRUE);
          if ($ret['error_count'] > 0) {
            foreach ((array) $ret['errors'] as $error) {
              watchdog('mailchimp', $error['email_address'] . ': ' . $error['message'], array(), WATCHDOG_ERROR);
            }
          }
        }
        $count += $ret['success_count'];
      }
      watchdog('mailchimp', 'Updated !count records in MailChimp', array(
        '!count' => $count,
      ), WATCHDOG_NOTICE);
    }
  }
}

/**
 * Implementation of hook_menu.
 */
function mailchimp_menu() {
  $items = array();
  $items['mailchimp/subscribe'] = array(
    'page callback' => 'drupal_get_form',
    'page arguments' => array(
      'mailchimp_subscribe_form',
    ),
    'title' => 'Newsletter Subscription',
    'type' => MENU_CALLBACK,
    'access callback' => TRUE,
  );
  $items['mailchimp/subscribe/message'] = array(
    'page callback' => 'mailchimp_subscribe_message',
    'title' => 'MailChimp Subscription Message',
    'type' => MENU_CALLBACK,
    'access callback' => TRUE,
  );
  $items['mailchimp/reset'] = array(
    'page callback' => 'drupal_get_form',
    'page arguments' => array(
      'mailchimp_reset',
    ),
    'type' => MENU_CALLBACK,
    'access arguments' => array(
      'administer site configuration',
    ),
  );
  $items['mailchimp/unsubscribe'] = array(
    'page callback' => 'drupal_get_form',
    'page arguments' => array(
      'mailchimp_unsubscribe_form',
    ),
    'title' => 'Newsletter Unsubscribe',
    'type' => MENU_CALLBACK,
    'access callback' => TRUE,
  );
  $items['mailchimp/unsubscribe/success'] = array(
    'page callback' => 'mailchimp_unsubscribe_success',
    'title' => 'Unsubscription Confirmed',
    'type' => MENU_CALLBACK,
    'access callback' => TRUE,
  );
  $items['mailchimp/unsubscribe/failure'] = array(
    'page callback' => 'mailchimp_unsubscribe_failure',
    'title' => 'Unsubscription Failed',
    'type' => MENU_CALLBACK,
    'access callback' => TRUE,
  );
  $items['admin/settings/mailchimp'] = array(
    'title' => 'MailChimp',
    'description' => 'Manage MailChimp Settings.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array(
      'mailchimp_admin_settings',
    ),
    'access arguments' => array(
      'administer site configuration',
    ),
    'type' => MENU_NORMAL_ITEM,
  );

  // optional
  return $items;
}
function mailchimp_reset() {
  variable_del('mailchimp_username');
  variable_del('mailchimp_password');
  drupal_goto('admin/settings/mailchimp');
}
function mailchimp_admin_settings() {
  module_load_include('php', 'mailchimp', 'MCAPI.class');
  $form['mailchimp_account_info'] = array(
    '#type' => 'fieldset',
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
    '#title' => 'MailChimp Account Information',
  );

  // only show the list selection forms if account info provided
  $username = variable_get('mailchimp_username', FALSE);
  $password = variable_get('mailchimp_password', FALSE);
  if ($username && $password) {
    $form['mailchimp_account_info']['mailchimp_setup_account'] = array(
      '#value' => t('Current configured account is for: @username.', array(
        '@username' => $username,
      )),
    );
    $form['mailchimp_account_info']['reset'] = array(
      '#value' => l('Click here to login as a different user.', 'mailchimp/reset'),
    );
    $q = new MCAPI($username, $password);
    if (!$q->errorCode) {
      $lists = $q
        ->lists();
      if (!empty($lists)) {
        $form['mailchimp_lists'] = array(
          '#type' => 'fieldset',
          '#collapsible' => FALSE,
          '#title' => 'MailChimp Subscription Lists',
        );
        foreach ($lists as $list) {
          $form['mailchimp_lists']['mailchimp_list_' . $list['id']] = array(
            '#type' => 'fieldset',
            '#collapsible' => TRUE,
            '#collapsed' => TRUE,
            '#title' => $list['name'],
          );

          // Add a row of checkboxes for role enabling.
          $form['mailchimp_lists']['mailchimp_list_' . $list['id']]['mailchimp_list_' . $list['id'] . '_roles'] = array(
            '#type' => 'fieldset',
            '#title' => t('Roles'),
            '#description' => t('Choose which roles may subscribe to this list. Select the anonymous user role to have the list appear on the !subscribe page. Select the authenticated user role to have the list appear on the !signup page. For all other roles, the list will appear on the settings page for users with that role.', array(
              '!subscribe' => l(t('Newsletter Subscription'), 'mailchimp/subscribe'),
              '!signup' => l(t('User Registration'), 'user/register'),
            )),
            '#tree' => FALSE,
          );
          foreach (user_roles() as $rid => $name) {
            $form['mailchimp_lists']['mailchimp_list_' . $list['id']]['mailchimp_list_' . $list['id'] . '_roles']['mailchimp_list_' . $list['id'] . '_role_' . $rid] = array(
              '#type' => 'checkbox',
              '#title' => $name,
              '#default_value' => variable_get('mailchimp_list_' . $list['id'] . '_role_' . $rid, 0),
            );
          }
          $form['mailchimp_lists']['mailchimp_list_' . $list['id']]['mailchimp_list_' . $list['id'] . '_description'] = array(
            '#type' => 'textarea',
            '#title' => t('List Description'),
            '#default_value' => variable_get('mailchimp_list_' . $list['id'] . '_description', ''),
            '#description' => t('This description will be shown to the user on the list signup and user account settings pages'),
          );
          $form['mailchimp_lists']['mailchimp_list_' . $list['id']]['mailchimp_list_' . $list['id'] . '_listtype'] = array(
            '#type' => 'select',
            '#title' => t('Subscription Method'),
            '#options' => array(
              'optin' => "Opt-in",
              'optin' => "Opt-in",
              'optout' => 'Opt-out',
              'required' => 'Required',
            ),
            '#default_value' => variable_get('mailchimp_list_' . $list['id'] . '_listtype', 'optin'),
            '#description' => t('<strong>Opt-in:</strong> Users must sign up to recieve messages.<br/><strong>Opt-out: </strong> Users are automatically signed up but may unsubscribe.<br/><strong>Required: </strong> Users will remain on the list as long as they have an account and cannot unsubscribe.'),
          );
          $form['mailchimp_lists']['mailchimp_list_' . $list['id']]['mailchimp_list_' . $list['id'] . '_doublein'] = array(
            '#type' => 'checkbox',
            '#title' => t('Require subscribers to Double Opt-in'),
            '#default_value' => variable_get('mailchimp_list_' . $list['id'] . '_doublein', 0),
            '#description' => t('New subscribers will be sent a link with an email they must follow to confirm their subscription.'),
          );
          $mergevars = $q
            ->listMergeVars($list['id']);
          if ($mergevars) {

            // Merge var fieldset
            $form['mailchimp_lists']['mailchimp_list_' . $list['id']]['mailchimp_list_' . $list['id'] . '_mergevars'] = array(
              '#type' => 'fieldset',
              '#title' => t('Merge Variables'),
              '#description' => t('Select Drupal user variables to send to Mailchimp as Merge Variables. Available Drupal variables are any Profile or Token variables for the given user. For more information on Merge Variables, see the !doc', array(
                '!doc' => l(t('Mailchimp Documentation'), 'http://server.iad. liveperson.net/hc/s-31286565/cmd/kbresource/kb-8214439208090042855/view_question!PAGETYPE?sq=merge%2bvariables&sf=101113&sg=0&st=188569&documentid=143258&action=view'),
              )),
              '#tree' => FALSE,
            );

            //@TODO: handle interest categories coming from MC
            $mergeoptions = mailchimp_get_merge_keys();
            foreach ($mergevars as $mergevar) {
              if ($mergevar['tag'] !== 'EMAIL') {
                $form['mailchimp_lists']['mailchimp_list_' . $list['id']]['mailchimp_list_' . $list['id'] . '_mergevars']['mailchimp_list_' . $list['id'] . '_merge_' . $mergevar['tag']] = array(
                  '#type' => 'select',
                  '#title' => $mergevar['name'],
                  '#options' => $mergeoptions,
                  '#default_value' => variable_get('mailchimp_list_' . $list['id'] . '_merge_' . $mergevar['tag'], ''),
                );
              }
            }
          }
        }
        $form['mailchimp_messages'] = array(
          '#type' => 'fieldset',
          '#collapsible' => TRUE,
          '#collapsed' => TRUE,
          '#title' => 'Messaging',
        );
        $form['mailchimp_messages']['mailchimp_subscription_success_message'] = array(
          '#type' => 'textarea',
          '#title' => t('Subscription Success Message'),
          '#default_value' => variable_get('mailchimp_subscription_success_message', SUBSCRIPTION_SUCCESS),
        );
        $form['mailchimp_messages']['mailchimp_subscription_failure_message'] = array(
          '#type' => 'textarea',
          '#title' => t('Subscription Failure Message'),
          '#default_value' => variable_get('mailchimp_subscription_failure_message', SUBSCRIPTION_FAILURE),
        );
        $form['mailchimp_messages']['mailchimp_unsubscription_success_message'] = array(
          '#type' => 'textarea',
          '#title' => t('Unsubscription Success Message'),
          '#default_value' => variable_get('mailchimp_unsubscription_success_message', UNSUBSCRIPTION_SUCCESS),
        );
        $form['mailchimp_messages']['mailchimp_unsubscription_failure_message'] = array(
          '#type' => 'textarea',
          '#title' => t('Unsubscription Failure Message'),
          '#default_value' => variable_get('mailchimp_unsubscription_failure_message', UNSUBSCRIPTION_FAILURE),
        );
        $form['mailchimp_user_register'] = array(
          '#type' => 'checkbox',
          '#title' => t('Show Subscription Options on User Registration Page'),
          '#default_value' => variable_get('mailchimp_user_register', TRUE),
        );
        $form['mailchimp_user_edit'] = array(
          '#type' => 'checkbox',
          '#title' => t('Show Subscription Options on User Edit Screen'),
          '#default_value' => variable_get('mailchimp_user_edit', TRUE),
        );
        $form['mailchimp_cron'] = array(
          '#type' => 'checkbox',
          '#title' => t('Sync Required Lists During Cron'),
          '#default_value' => variable_get('mailchimp_cron', FALSE),
          '#description' => t('If this is set, users will be subscribed to the required list during cron runs. Otherwise subscription will take place when a user is added/edited.'),
        );
      }
      else {
        drupal_set_message(t('You do not have any valid MailChimp mailing lists.'));
      }
    }
    else {
      if (FALSE && $q->errorCode === 'INVALID_LOGIN') {
        drupal_set_message(t('Could not login to mailchimp. Please check your username and password.'), "error");
      }
      else {
        if ($q->errorMessage) {
          drupal_set_message(t('Could not retrieve info for mailchimp. The following error was returned: %error.', array(
            '%error' => $q->errorMessage,
          )), "error");
        }
        else {
          drupal_set_message(t('Could not retrieve info for mailchimp for an unknown reason. Please try again later'), "error");
        }
      }
    }
  }
  else {
    $form['mailchimp_account_info']['mailchimp_username'] = array(
      '#type' => 'textfield',
      '#title' => t('Mailchimp username'),
      '#required' => TRUE,
      '#default_value' => variable_get('mailchimp_username', ''),
      '#description' => t('The username used to login to your MailChimp account.'),
    );
    $form['mailchimp_account_info']['mailchimp_password'] = array(
      '#type' => 'password',
      '#title' => t('Mailchimp password'),
      '#required' => TRUE,
      '#default_value' => variable_get('mailchimp_password', ''),
      '#description' => t('The password used to login to your MailChimp account.'),
    );
  }
  return system_settings_form($form);
}
function mailchimp_subscribe_form() {
  global $user;
  if ($user->uid) {
    drupal_set_message(t('You can manage your newsletter subscriptions from your ' . l('user account page', 'user') . '.'));
  }
  else {
    if ($q = _mailchimp_get_api_object()) {
      $lists = _mailchimp_get_available_lists($user, $q);
      if (count($lists) > 0) {
        foreach ($lists as $list) {
          $form['list_' . $list['id']] = array(
            '#type' => 'fieldset',
            '#title' => $list['name'],
            '#collapsible' => TRUE,
            '#tree' => TRUE,
          );
          $checked = variable_get('mailchimp_list_' . $list['id'] . '_listtype', 'optin') == "optout" ? 1 : 0;
          $form['list_' . $list['id']][$list['id']] = array(
            '#type' => 'checkbox',
            '#title' => t('Subscribe to the @newsletter newsletter', array(
              '@newsletter' => $list['name'],
            )),
            '#default_value' => $checked,
            '#description' => variable_get('mailchimp_list_' . $list['id'] . '_description', ''),
          );
          foreach ((array) $q
            ->listMergeVars($list['id']) as $mergevar) {
            $form['list_' . $list['id']][$mergevar['tag']] = array(
              '#type' => 'textfield',
              '#title' => $mergevar['name'],
            );
          }
          if ($intgroup = $q
            ->listInterestGroups($list['id'])) {
            $form['list_' . $list['id']][$intgroup['name']] = array(
              '#type' => 'fieldset',
              '#title' => $intgroup['name'],
            );
            foreach ((array) $intgroup['groups'] as $group) {
              $form['list_' . $list['id']][$intgroup['name']][$group] = array(
                '#type' => $intgroup['form_field'],
                '#title' => $group,
              );
            }
          }
        }
        $form['submit'] = array(
          '#type' => 'submit',
          '#value' => t('Sign Up!'),
        );
      }
    }
    return $form;
  }
}
function mailchimp_subscribe_form_submit($form, &$form_state) {
  global $user;
  if ($q = _mailchimp_get_api_object()) {
    $lists = _mailchimp_get_available_lists($user, $q);
    $success = TRUE;
    foreach ($lists as $list) {
      $lid = $list['id'];
      $sub_info = $q
        ->listMemberInfo($lid, $form_state['values']['list_' . $lid]['EMAIL']);
      $is_subscribed = @$sub_info['status'] == 'subscribed';

      // add users who are not subscribed and checked the list
      if ($form_state['values']['list_' . $list['id']][$lid] && !$is_subscribed) {
        $success = $success && _mailchimp_subscribe_user($list, $form_state['values']['list_' . $list['id']], TRUE, $q);
      }
    }
  }
  drupal_goto('mailchimp/subscribe/message', 'success=' . $success);
}
function mailchimp_subscribe_message() {
  if ($_GET['success']) {
    return variable_get('mailchimp_subscription_success_message', SUBSCRIPTION_SUCCESS);
  }
  else {
    return variable_get('mailchimp_subscription_failure_message', SUBSCRIPTION_FAILURE);
  }
}
function mailchimp_unsubscribe_form($form_values = array()) {
  $form = array();
  $form['intro'] = array(
    '#type' => 'markup',
    '#value' => t('Use this form to unsubscribe from all of our newsletters.'),
  );
  $form['EMAIL'] = array(
    '#type' => 'textfield',
    '#title' => t('Email Address'),
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Unsubscribe'),
  );
  return $form;
}
function mailchimp_unsubscribe_form_submit($form, &$form_state) {
  if ($q || ($q = _mailchimp_get_api_object())) {
    $success = TRUE;
    foreach ((array) $q
      ->lists() as $list) {
      $success = $success && _mailchimp_unsubscribe_user($list, $form_state['values']['EMAIL'], TRUE, $q);
      if ($success) {
        drupal_set_message(variable_get('mailchimp_unsubscription_success_message', UNSUBSCRIPTION_SUCCESS));
      }
      else {
        drupal_set_message(variable_get('mailchimp_unsubscription_failure_message', UNSUBSCRIPTION_FAILURE));
      }
    }
  }
}
function mailchimp_unsubscribe_form_validate($form, &$form_state) {
  if (!$form_state['values']['EMAIL']) {
    form_set_error('EMAIL', t('Please enter your email address.'));
  }
  else {
    if ($q || ($q = _mailchimp_get_api_object())) {
      $subscribed = FALSE;
      foreach ((array) $q
        ->lists() as $list) {
        $subscribed = $subscribed || _mailchimp_is_subscribed($list['id'], $form_state['values']['EMAIL'], $q);
      }
      if (!$subscribed) {
        form_set_error('', t('That email address could not be found.'));
      }
    }
    else {
      form_set_error('', t('There was an error processing your request. Please try again later.'));
    }
  }
}

/**
 * Implementation of hook_mailchimp_merge_keys
 */
function mailchimp_mailchimp_merge_keys() {
  $out = array(
    0 => '<none>',
  );
  $user_fields = array(
    'name' => t('Username'),
    'mail' => t('Email Address'),
    'uid' => t('User ID'),
    'signature' => t("User's Signature"),
  );
  foreach ($user_fields as $key => $field) {
    $out[$key] = t('User: !field', array(
      '!field' => $field,
    ));
  }
  if (function_exists('_profile_get_fields')) {
    $categories = profile_categories();
    if (!empty($categories)) {
      foreach ($categories as $category) {
        $result = _profile_get_fields($category['name'], $register);
        while ($field = db_fetch_object($result)) {
          $out[$field->name] = t('Profile: !cat - !field', array(
            '!cat' => $field->category,
            '!field' => $field->title,
          ));
        }
      }
    }
  }
  if (function_exists('token_get_list')) {
    $tokens = token_get_list(array(
      'user',
      'order',
    ));
    foreach ($tokens['user'] as $token => $name) {
      $out['token_' . $token] = t('Token: !field', array(
        '!field' => $name,
      ));
    }
  }
  return $out;
}

/**
 * Implementation of hook_mailchimp_merge_values
 */
function mailchimp_mailchimp_merge_values($user) {
  $out = array();
  $out = (array) $user;
  $out = array_merge($out, _mailchimp_get_user_tokens($user));
  return $out;
}

/**
 * Get the user tokens for merging
 */
function _mailchimp_get_user_tokens($user) {
  $out = array();
  if (function_exists('token_get_values')) {
    $vars = token_get_values('user', $user);
    foreach ($vars->tokens as $key => $value) {
      $out['token_' . $value] = $vars->values[$key];
    }
  }
  return $out;
}

/**
 * Get the available merge var keys
 */
function mailchimp_get_merge_keys() {
  return module_invoke_all('mailchimp_merge_keys');
}

/**
 * Get all the potential merge var values for a given user
 */
function mailchimp_get_merge_values($uid) {
  if ($user = user_load(array(
    'uid' => $uid,
  ))) {
    return module_invoke_all('mailchimp_merge_values', $user);
  }
  return array();
}

/**
 * Get the relevent merge vars for the given user for the given list
 */
function _mailchimp_load_user_list_mergevars($uid, $list_id, $mergevars) {
  $account = mailchimp_get_merge_values($uid);
  $uservars = array(
    'EMAIL' => $account['mail'],
  );
  foreach ($mergevars as $mergevar) {
    if ($key = variable_get('mailchimp_list_' . $list_id . '_merge_' . $mergevar['tag'], '')) {
      $uservars[$mergevar['tag']] = $account[$key];
    }
  }
  return $uservars;
}

/**
 * Check if the given user is subscribed to the given list
 */
function _mailchimp_is_subscribed($listid, $mail, $q = NULL) {
  $is_subscribed = FALSE;
  if ($q || ($q = _mailchimp_get_api_object())) {
    $sub_info = $q
      ->listMemberInfo($listid, $mail);
    $is_subscribed = @$sub_info['status'] == 'subscribed';
  }
  return $is_subscribed;
}

/**
 * Subscribe the given user to the given list if he/she is not already subscribed
 */
function _mailchimp_subscribe_user($list, $merge_vars, $message = TRUE, $q = NULL) {
  if ($q || ($q = _mailchimp_get_api_object())) {
    $double_optin = variable_get('mailchimp_list_' . $list['id'] . '_doublein', 0);
    if (_mailchimp_is_subscribed($list['id'], $merge_vars['EMAIL'], $q)) {
      $success = $q
        ->listUpdateMember($list['id'], $merge_vars['EMAIL'], $merge_vars);
    }
    else {
      $success = $q
        ->listSubscribe($list['id'], $merge_vars['EMAIL'], $merge_vars, 'html', $double_optin);
      if ($message && $success && $double_optin) {
        drupal_set_message(t('You have chosen to subscribe to %list. An email will be sent to your address. Click the link in the email to confirm the subscription.', array(
          '%list' => $list['name'],
        )));
      }
      else {
        if ($message && $success) {
          drupal_set_message(t('You have subscribed to %list.', array(
            '%list' => $list['name'],
          )));
        }
      }
    }
  }
  if ($success) {
    watchdog('mailchimp', '@email has subscribed to @list.', array(
      '@email' => $merge_vars['EMAIL'],
      '@list' => $list['name'],
    ), WATCHDOG_NOTICE);
  }
  else {
    watchdog('mailchimp', '@email has failed to subscribed to @list.', array(
      '@email' => $merge_vars['EMAIL'],
      '@list' => $list['name'],
    ), WATCHDOG_WARNING);
  }
  return $success;
}

/**
 * Update the given user's subscrition to the given list
 */
function _mailchimp_update_user($list, $mail, $merge_vars, $q = NULL) {
  if ($q || ($q = _mailchimp_get_api_object())) {
    $q
      ->listUpdateMember($list['id'], $mail, $merge_vars);
  }
  return $success;
}

/**
 * Unsubscribe the given user to the given list
 */
function _mailchimp_unsubscribe_user($list, $mail, $message = TRUE, $q = NULL) {
  if ($q || ($q = _mailchimp_get_api_object())) {
    if (_mailchimp_is_subscribed($list['id'], $mail, $q)) {
      $success = $q
        ->listUnsubscribe($list['id'], $mail, FALSE);
      if ($message && $success) {
        drupal_set_message(t('You have unsubscribed from %list.', array(
          '%list' => $list['name'],
        )));
      }
    }
  }
  return TRUE;

  //$success; // the mailchim api seems to always return FALSE on unsubscribe operations
}

/**
 * Get all of the lists that the given user can subscribe to
 */
function _mailchimp_get_available_lists($user, $q = NULL) {
  $lists = array();
  if ($q || ($q = _mailchimp_get_api_object())) {
    foreach ((array) $q
      ->lists() as $list) {
      if (!empty($list)) {
        foreach ((array) $user->roles as $rid => $info) {
          if (variable_get('mailchimp_list_' . $list['id'] . '_role_' . $rid, 0)) {
            $lists[$list['id']] = $list;
          }
        }
      }
    }
  }
  return $lists;
}

/**
 * Get all of the lists that the given user must be subscribed to
 */
function _mailchimp_get_required_lists($lists) {
  foreach ($lists as $key => $list) {
    if (variable_get('mailchimp_list_' . $list['id'] . '_listtype', '') !== 'required') {
      unset($lists[$key]);
    }
  }
  return $lists;
}

/**
 * Get a Mailchimp API object for communication with the mailchimp server
 */
function _mailchimp_get_api_object() {
  module_load_include('php', 'mailchimp', 'MCAPI.class');
  $q = new MCAPI(variable_get('mailchimp_username', ''), variable_get('mailchimp_password', ''));
  if ($q->errorCode) {
    watchdog('mailchimp', $q->errorMessage, array(), WATCHDOG_ERROR);
    return NULL;
  }
  return $q;
}

Functions

Namesort descending Description
mailchimp_admin_settings
mailchimp_cron Implementation of hook_cron. Resubscribes all users to the required lists if the user has chosen to do so.
mailchimp_form_user_register_alter Implementation of hook_form_alter() . Add subscription form to registration page
mailchimp_get_merge_keys Get the available merge var keys
mailchimp_get_merge_values Get all the potential merge var values for a given user
mailchimp_mailchimp_merge_keys Implementation of hook_mailchimp_merge_keys
mailchimp_mailchimp_merge_values Implementation of hook_mailchimp_merge_values
mailchimp_menu Implementation of hook_menu.
mailchimp_reset
mailchimp_subscribe_form
mailchimp_subscribe_form_submit
mailchimp_subscribe_message
mailchimp_unsubscribe_form
mailchimp_unsubscribe_form_submit
mailchimp_unsubscribe_form_validate
mailchimp_user
_mailchimp_get_api_object Get a Mailchimp API object for communication with the mailchimp server
_mailchimp_get_available_lists Get all of the lists that the given user can subscribe to
_mailchimp_get_required_lists Get all of the lists that the given user must be subscribed to
_mailchimp_get_user_tokens Get the user tokens for merging
_mailchimp_is_subscribed Check if the given user is subscribed to the given list
_mailchimp_load_user_list_mergevars Get the relevent merge vars for the given user for the given list
_mailchimp_subscribe_user Subscribe the given user to the given list if he/she is not already subscribed
_mailchimp_unsubscribe_user Unsubscribe the given user to the given list
_mailchimp_update_user Update the given user's subscrition to the given list

Constants