You are here

function mailchimp_user_insert in Mailchimp 7

Implements hook_user_insert().

File

./mailchimp.module, line 37
Mailchimp module.

Code

function mailchimp_user_insert(&$edit, $account, $category) {
  if ($q = _mailchimp_get_api_object()) {
    foreach ((array) _mailchimp_get_available_lists($account) as $list) {

      // first deal with all required lists
      if ($list->listtype == MAILCHIMP_LISTTYPE_REQUIRED) {

        // process immediately
        if (!variable_get('mailchimp_cron', FALSE)) {

          // determine if a user is allowed in a given list
          $is_allowed = FALSE;
          $roles = $edit['roles'];
          if (!is_array($roles)) {
            $roles = $account->roles;
          }
          foreach ($list->roles as $key => $value) {
            if (array_key_exists($key, $roles)) {
              $is_allowed = TRUE;
              break;
            }
          }

          // they are allowed, update or subscribe
          if ($is_allowed) {
            $userinfo = _mailchimp_load_user_list_mergevars($account, $list->id);
            $userinfo['EMAIL'] = $edit['mail'];
            _mailchimp_subscribe_user($list, $account->mail, $userinfo, FALSE, $q);
          }
          else {
            _mailchimp_unsubscribe_user($list, $account->mail, FALSE, $q);
          }
        }
        else {
          $result = db_query("SELECT uid FROM {mailchimp_user} WHERE uid = :uid", array(
            ':uid' => $account->uid,
          ));
          if ($result
            ->rowCount() == 0) {
            db_insert('mailchimp_user')
              ->fields(array(
              'uid' => $account->uid,
              'status' => MAILCHIMP_USERSTATUS_PENDING,
            ))
              ->execute();
          }
        }
      }
      else {
        $ret = TRUE;
        $selected = @$edit['mailchimp_list_' . $list->id];
        if ($selected) {
          $merge_vars = _mailchimp_load_user_list_mergevars($account, $list->id);

          // include interest groups
          if (!empty($edit['mailchimp_list_' . $list->id . '_INTERESTS'])) {
            $merge_vars['INTERESTS'] = implode(',', array_filter($edit['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,
          )));
        }
      }
    }
  }
}