You are here

function mailchimp_subscribe_auth_form_submit in Mailchimp 6.2

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

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

1 string reference to 'mailchimp_subscribe_auth_form_submit'
mailchimp_subscribe_auth_form in ./mailchimp.module
Maichimp authenticated user subscription form.

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(array(
        'uid' => $form_state['values']['uid'],
      ));
    }
    else {
      global $user;
      $account = $user;
    }
    $lists = $form_state['values']['lists'];
    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);
        }
        else {
          if ($selected) {

            // subscribe the user if they are not previously subscribed or update existing subscriptions
            $merge_vars = _mailchimp_load_user_list_mergevars($account->uid, $list->id, $q
              ->listMergeVars($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 (isset($form_state['values']['interest_groups_' . $list->id]) && is_array($form_state['values']['interest_groups_' . $list->id])) {
              foreach ($form_state['values']['interest_groups_' . $list->id] as $key => $group) {
                $merge_vars['GROUPINGS'][] = array(
                  'id' => $key,
                  'groups' => _mailchimp_implode_interest_groups($group),
                );
              }
            }
            $ret = _mailchimp_subscribe_user($list, $account->mail, $merge_vars, TRUE, $q);
          }
        }
        if (!$ret) {
          watchdog('mailchimp', 'MCAPI Error: %errormsg', array(
            '%errormsg' => $q->errorMessage,
          ), WATCHDOG_ERROR);
        }
      }
    }
  }
}