You are here

function mailchimp_subscribe_auth_form_submit in Mailchimp 7

Same name and namespace in other branches
  1. 6.2 mailchimp.module \mailchimp_subscribe_auth_form_submit()

Submit handler to add users to lists when editing/creating a user

File

./mailchimp.module, line 278
Mailchimp module.

Code

function mailchimp_subscribe_auth_form_submit($form, &$form_state) {
  if ($q = _mailchimp_get_api_object()) {
    $account = new stdClass();
    if (!empty($form_state['values']['uid'])) {
      $account = user_load($form_state['values']['uid']);
    }
    else {
      $account = $form_state['user'];
    }
    $lists = _mailchimp_get_available_lists($account);
    foreach ($lists as $list) {

      // ignore required lists, they are handled via hook_user
      if ($list->listtype !== MAILCHIMP_LISTTYPE_REQUIRED) {
        $is_subscribed = _mailchimp_is_subscribed($list->id, $account->mail, $q);
        $ret = TRUE;
        $selected = @$form_state['values']['mailchimp_list_' . $list->id];

        // unsubscribe a subscribed user who unchecked the box when not registering
        if ($is_subscribed && !$selected && $form['#id'] != 'user-register') {
          $ret = _mailchimp_unsubscribe_user($list, $account->mail, TRUE, $q);
        }
        elseif ($selected) {

          // subscribe the user if they are not previously subscribed or update existing subscriptions
          $merge_vars = _mailchimp_load_user_list_mergevars($account, $list->id);

          // include updated email address if already subscribed
          if (!empty($form_state['values']['mail']) && $is_subscribed) {
            $merge_vars['EMAIL'] = $form_state['values']['mail'];
          }

          // include interest groups
          if (!empty($form_state['values']['mailchimp_list_' . $list->id . '_INTERESTS'])) {
            $merge_vars['INTERESTS'] = implode(',', array_filter($form_state['values']['mailchimp_list_' . $list->id . '_INTERESTS']));
          }
          $ret = _mailchimp_subscribe_user($list, $account->mail, $merge_vars, TRUE, $q);
        }
        if (!$ret) {
          drupal_set_message(t('There was a problem with your newsletter signup: @msg', array(
            '@msg' => $q->errorMessage,
          )));
        }
      }
    }
  }
}