You are here

campaignmonitor.module in Campaign Monitor 6.3

Module that plugs in Campaign Monitor functionality to your Drupal web site. For Campaign Monitor information see: http://www.campaignmonitor.com/

This module uses the CampaignMonitor PHP API. For all credit and information about this PHP API see By ssherriff: http://code.google.com/p/campaignmonitor-php/

File

campaignmonitor.module
View source
<?php

/**
 * @file
 * Module that plugs in Campaign Monitor functionality to your Drupal web site.
 * For Campaign Monitor information see: http://www.campaignmonitor.com/
 *
 * This module uses the CampaignMonitor PHP API. For all credit and information
 * about this PHP API see By ssherriff: http://code.google.com/p/campaignmonitor-php/
 */
define('CM_SUBSCRIPTION_SUCCESS', t('You have been successfully subscribed to %list.'));
define('CM_SUBSCRIPTION_ERROR', t('We were unable to subscribe you at this time. Please try again later.'));
define('CM_UNSUBSCRIPTION_SUCCESS', t('You have been successfully unsubscribed.'));
define('CM_UNSUBSCRIPTION_ERROR', t('We were unable to unsubscribe you at this time. Please try again later.'));
define('CM_ERROR', t('There is an error with the newsletter server. Please try again later'));
define('CM_CHECKBOX_DISPLAY_TEXT_DEFAULT', t('Available Newsletters'));
define('CM_USERPAGE_DISPLAY_TEXT_DEFAULT', t('Available Newsletters'));
define('CM_CONNECTION_TIMEOUT_DEFAULT', 15);
define('CM_API_KEY', 'campaignmonitor_api_key');
define('CM_CLIENT_ID', 'campaignmonitor_client_id');
define('CM_DISPLAY_ON', 'campaignmonitor_display_on');
define('CM_CHECKBOX_DISPLAY_TEXT', 'campaignmonitor_checkboxdisplaytext');
define('CM_USERPAGE_DISPLAY_TEXT', 'campaignmonitor_userpagedisplaytext');
define('CM_PAST_CAMPAIGN_URL', 'campaignmonitor_pastcampaignurl');
define('CM_CONNECTION_TIMEOUT', 'campaignmonitor_connection_timeout');
define('CM_LISTS', 'campaignmonitor_lists');
define('CM_LISTS_CF', 'campaignmonitor_lists_customfields');
@(require_once drupal_get_path('module', 'campaignmonitor') . '/lib/CMBase.php');

/**
 * Implementation of hook_help().
 */
function campaignmonitor_help($path, $arg) {
  switch ($path) {
    case 'admin/settings/campaignmonitor':
      return '<p>' . t('Use your API key and other keys to have users register for a mailing list setup through Campaign Monitor.') . '</p>';
  }
}

/**
 * Implementation of hook_perm().
 */
function campaignmonitor_perm() {
  return array(
    'administer campaignmonitor',
    'access archive',
    'join newsletter',
  );
}

/**
 * Implementation of hook_menu().
 */
function campaignmonitor_menu() {
  $items = array();
  $items['admin/settings/campaignmonitor'] = array(
    'title' => 'Campaign Monitor',
    'description' => 'Setup Campaign Monitor values.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array(
      'campaignmonitor_admin_settings_form',
    ),
    'access arguments' => array(
      'administer campaignmonitor',
    ),
    'type' => MENU_NORMAL_ITEM,
    'file' => 'includes/campaignmonitor.admin.inc',
  );
  $items['newsletter_archive'] = array(
    'title' => 'Newsletter Archive',
    'page callback' => 'campaignmonitor_newsletter_archive',
    'access arguments' => array(
      'access archive',
    ),
    'type' => MENU_SUGGESTED_ITEM,
  );
  $items['user/%user/newsletters'] = array(
    'title' => 'My Newsletters',
    'page callback' => 'drupal_get_form',
    'page arguments' => array(
      'campaignmonitor_user_page_form',
    ),
    'access callback' => 'campaignmonitor_user_page_access',
    'access arguments' => array(
      1,
    ),
    'type' => MENU_LOCAL_TASK,
    'file' => 'includes/campaignmonitor.user_page.inc',
    'weight' => 5,
  );
  return $items;
}

/**
 * Access callback for the user newsletters page.
 */
function campaignmonitor_user_page_access($account) {
  global $user;
  $display_on = variable_get(CM_DISPLAY_ON, array());
  if ($display_on['userpage'] && $user->uid && $user->uid == $account->uid && user_access('join newsletter')) {
    return TRUE;
  }
  return FALSE;
}

/**
 * Implementation of hook_form_alter().
 * 
 */
function campaignmonitor_form_alter(&$form, $form_state, $form_id) {
  $display_on = variable_get(CM_DISPLAY_ON, array());
  if ('contact_mail_page' == $form_id && $display_on['contact'] != '0' || 'user_register' == $form_id && $display_on['registration'] != '0' && user_access('join newsletter')) {
    $api_key = variable_get(CM_API_KEY, '');
    $client_id = variable_get(CM_CLIENT_ID, '');
    $lists = campaignmonitor_get_available_lists();
    $not_empty = FALSE;
    $options = array();
    foreach ($lists as $list_id => $list) {
      if ($list->oncontactpage && 'contact_mail_page' == $form_id || $list->onregopage && 'user_register' == $form_id) {
        $options[$list_id] = $list->name;
        $not_empty = TRUE;
      }
    }
    if ($not_empty) {
      $form['subscribe_newsletter'] = array(
        '#type' => 'checkboxes',
        '#title' => check_plain(t(variable_get(CM_CHECKBOX_DISPLAY_TEXT, CM_CHECKBOX_DISPLAY_TEXT_DEFAULT))),
        '#options' => $options,
        '#weight' => 99,
      );
      $form['submit']['#weight'] = 100;
      $form['#submit'][] = '_campaignmonitor_altered_form_submit';
    }
  }
}
function _campaignmonitor_altered_form_submit($form, &$form_state) {
  $form_values = $form_state['values'];
  $listids = $form_values['subscribe_newsletter'];
  if (count($listids) > 0) {

    // Replace api_key and list_id with your own details
    $api_key = variable_get(CM_API_KEY, '');
    foreach ($listids as $list_id) {
      if ($list_id) {
        if (_campaignmonitor_add_subscriber($api_key, $list_id, check_plain($form_values['name']), check_plain($form_values['mail']))) {

          // Only add to message if the subscriber succeeded.
          if ($form['form_id']['#value'] == 'contact_mail_page') {
            $form_values['message'] .= "\n\n" . t('You have been subscribed to newsletter(s).');
          }
        }
      }
    }
  }
}

/**
 * Implementation of hook_block().
 */
function campaignmonitor_block($op = 'list', $delta = 0, $edit = array()) {
  switch ($op) {
    case 'list':
      return campaignmonitor_block_list();
    case 'configure':
    case 'save':

      // no additional configuration options
      break;
    case 'view':
    default:
      $lists = campaignmonitor_get_available_lists();
      $list = $lists[$delta];
      $block['subject'] = $list->name;
      $block['content'] = theme('campaignmonitor_block_content', $delta);
      return $block;
  }
}

/**
 * Implementation of hook_theme().
 */
function campaignmonitor_theme() {
  return array(
    'campaignmonitor_block_content' => array(
      'template' => 'campaignmonitor-block-content',
      'arguments' => array(
        'list_id' => NULL,
      ),
    ),
  );
}

/**
 * Returns a list of blocks in a form suitable for hook_block() when $op == list:
 * A block is returned for each CampaignMonitor list chosen in admin settings
 */
function campaignmonitor_block_list() {
  $blocks = array();
  $lists = campaignmonitor_get_available_lists();
  foreach ($lists as $list_id => $list) {

    // If list==0 that means that list is not chosen, don't create a block
    if ($list != '0') {
      $blocks[$list_id]['info'] = t('Subscribe to @list_name', array(
        '@list_name' => $list->name,
      ));
    }
  }
  return $blocks;
}
function campaignmonitor_subscribe_form(&$form_state, $list_id) {
  global $user;
  $uid = $user->uid;
  $name = '';
  $email = '';
  $subscriber_custom_fields = array();
  $default = FALSE;
  $lists = campaignmonitor_get_available_lists();
  $list = $lists[$list_id];

  // try to get name from default key values
  $account = campaignmonitor_get_field_key_values($uid);
  $name = $account[$list->namekey];
  if ($user->uid != 0) {
    $email = $user->mail;
    if (_campaignmonitor_is_subscribed(variable_get(CM_API_KEY, ''), $list_id, $email)) {
      $default = TRUE;

      // Also if subscribed get name
      $subscriber = _campaignmonitor_get_subscriber(variable_get(CM_API_KEY, ''), $list_id, $email);
      $name = $subscriber['name'];
    }
    else {
      $default = FALSE;
    }
  }
  if ($list->displayname) {
    $form['name'] = array(
      '#type' => 'textfield',
      '#title' => t('Name'),
      '#size' => 20,
      '#maxlength' => 50,
      '#required' => TRUE,
      '#default_value' => $name,
    );
  }
  $form['email'] = array(
    '#type' => 'textfield',
    '#title' => t('Email'),
    '#size' => 20,
    '#maxlength' => 100,
    '#required' => TRUE,
    '#default_value' => $email,
  );
  $custom_fields = _campaignmonitor_get_custom_fields(variable_get(CM_API_KEY, ''), $list_id);
  foreach ($custom_fields as $field) {
    $key = str_replace(array(
      '[',
      ']',
    ), '', $field['Key']);
    $saved_cfs = $list->customfields;
    $display_cf = FALSE;
    if ($saved_cfs == NULL) {

      // case that upgraded and haven't gone to admin page yet, make sure to display as that would keep same behavior
      $display_cf = TRUE;
    }
    else {
      $saved_cf = $saved_cfs[$key];
      $display_cf = $saved_cf->display;
    }
    if ($display_cf) {
      if ($field['DataType'] == 'Text') {
        $form[$key] = array(
          '#type' => 'textfield',
          '#title' => t($field['FieldName']),
          '#size' => 20,
          '#maxlength' => 100,
          '#default_value' => $subscriber['CustomFields'][$field['FieldName']],
        );
      }
      elseif ($field['DataType'] == 'MultiSelectOne') {
        $options = array();
        foreach ($field['FieldOptions']['string'] as $option) {
          $options[$option] = $option;
        }
        $_defaultvalue = $subscriber['CustomFields'][$field['FieldName']];
        if (empty($_defaultvalue)) {
          $defaultvalue = '';
        }
        else {
          $defaultvalue = $_defaultvalue;
        }
        $form[$key] = array(
          '#type' => 'select',
          '#title' => t($field['FieldName']),
          '#options' => $options,
          '#default_value' => $defaultvalue,
        );
      }
      elseif ($field['DataType'] == 'MultiSelectMany') {
        $options = array();
        foreach ($field['FieldOptions']['string'] as $option) {
          $options[$option] = $option;
        }
        $_defaultvalues = $subscriber['CustomFields'][$field['FieldName']];
        if (empty($_defaultvalues)) {
          $defaultvalues = array();
        }
        elseif (!is_array($_defaultvalues)) {
          $defaultvalues = array();
          $defaultvalues[] = $_defaultvalues;
        }
        else {
          $defaultvalues = array();
          foreach ($_defaultvalues as $dv) {
            $defaultvalues[] = $dv;
          }
        }
        $form[$key] = array(
          '#type' => 'checkboxes',
          '#title' => t($field['FieldName']),
          '#options' => $options,
          '#default_value' => $defaultvalues,
        );
      }
      elseif ($field['DataType'] == 'Number') {
        $form[$key] = array(
          '#type' => 'textfield',
          '#title' => t($field['FieldName']),
          '#size' => 20,
          '#maxlength' => 100,
          '#default_value' => $subscriber['CustomFields'][$field['FieldName']],
        );
      }
    }
  }

  /* $form['unsubscribe_newsletter'] = array(
     '#type'          => 'checkbox',
     '#title'         => t('Unsubscribe'),
     '#default_value' => $default,
     ); */
  $form['list_id'] = array(
    '#type' => 'hidden',
    '#value' => $list_id,
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  );
  return $form;
}
function campaignmonitor_subscribe_form_submit($form, &$form_state) {
  $form_values = $form_state['values'];

  // Replace api_key with your own details
  $api_key = variable_get(CM_API_KEY, '');
  $list_id = $form_values['list_id'];
  $name = check_plain($form_values['name']);
  $email = check_plain($form_values['email']);
  $custom_field_array = array();
  $lists = campaignmonitor_get_available_lists();
  $list = $lists[$list_id];

  // any cases other then these are when things are unchanged
  if (!$form_values['unsubscribe_newsletter']) {

    // this is the case where they now want to be subscribed, and weren't before
    $custom_fields = _campaignmonitor_get_custom_fields($api_key, $list_id);
    foreach ($custom_fields as $field) {
      $key = str_replace(array(
        '[',
        ']',
      ), '', $field['Key']);
      $saved_cfs = $list->customfields;
      $display_cf = FALSE;
      if ($saved_cfs == NULL) {

        // case that upgraded and haven't gone to admin page yet, make sure to display as that would keep same behavior
        $display_cf = TRUE;
      }
      else {
        $saved_cf = $saved_cfs[$key];
        $display_cf = $saved_cf->display;
      }
      if ($display_cf) {
        $custom_field_array[$field['FieldName']] = $form_values[$key];
      }
    }
    _campaignmonitor_add_subscriber($api_key, $list_id, $name, $email, $custom_field_array);
  }
  elseif ($form_values['unsubscribe_newsletter']) {

    // this is the case where they don't want to be subscribed, and were before
    _campaignmonitor_remove_subscriber($api_key, $list_id, $email);
  }
}
function campaignmonitor_newsletter_archive() {
  $url = variable_get(CM_PAST_CAMPAIGN_URL, '');
  if ($url == '') {
    $content = '<p>' . t('The past campaign URL has not been set. Please set this in the administration pages.') . '</p>';
  }
  else {
    $content = '<script type="text/javascript" src="' . variable_get(CM_PAST_CAMPAIGN_URL, '') . '"></script>';
  }
  return $content;
}
function campaignmonitor_get_available_lists() {
  $all_lists = variable_get('campaignmonitor_lists', '');
  $available_lists = array();
  if (!empty($all_lists)) {
    foreach ($all_lists as $key => $list) {
      $available_lists[$key] = $list;
    }
  }
  return $available_lists;
}

/* CUSTOM MODULE HOOKS */

/**
 * Get the available field keys
 */
function campaignmonitor_get_field_keys($reset = FALSE) {
  return module_invoke_all('campaignmonitor_field_keys', $reset);
}

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

/* END CUSTOM MODULE HOOKS */

/* IMPLEMENTATION OF CUSTOM MODULE HOOKS */

/**
 * Implementation of hook_campaignmonitor_field_keys
 */
function campaignmonitor_campaignmonitor_field_keys($reset = FALSE) {
  static $output;
  if (!isset($output) || $reset) {
    $output = array(
      0 => '<none>',
    );

    // Add user information fields.
    $user_fields = array(
      'name' => t('Username'),
      'mail' => t('Email Address'),
      'uid' => t('User ID'),
      'signature' => t("User's Signature"),
      'created' => t("User's Creation Date"),
      'access' => t("User's Last Access Date"),
    );
    foreach ($user_fields as $key => $field) {
      $output[$key] = t('User: @field', array(
        '@field' => $field,
      ));
    }

    // If the profile module is avaliable, get fields from it.
    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)) {
            $output[$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',
      ));
      if (is_array($tokens['user'])) {
        foreach ($tokens['user'] as $token => $name) {
          $output['token_' . $token] = t('Token: @field', array(
            '@field' => $name,
          ));
        }
      }
    }
  }
  return $output;
}

/**
 * Implementation of hook_campaignmonitor_field_key_values
 */
function campaignmonitor_campaignmonitor_field_key_values($user) {
  $out = array();
  $out = (array) $user;
  foreach ((array) $user as $key => $value) {
    if (is_array($value) && $key != 'role') {
      $out[$key] = implode('/', $value);
    }
    elseif (in_array($key, array(
      'login',
      'access',
      'created',
    ))) {
      $out[$key] = date('c', $value);
    }
    elseif ($key != 'roles') {
      $out[$key] = $value;
    }
  }
  $out = array_merge($out, _campaignmonitor_get_user_tokens($user));
  return $out;
}

/**
 * Get the user tokens for merging
 */
function _campaignmonitor_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;
}

/* END IMPLEMENTATION OF CUSTOM MODULE HOOKS */

/* TEMPLATE FUNCTIONS */

/**
 * Implementation of preprocess_campaignmontor_block_content(). Which adds a
 * newsletter archive link, if the archive URL is defined and user access is
 * granted.
 */
function template_preprocess_campaignmonitor_block_content(&$variables) {
  $variables['form'] = drupal_get_form('campaignmonitor_subscribe_form', $variables['list_id']);
  $past_campaign_url = variable_get(CM_PAST_CAMPAIGN_URL, FALSE);
  if (user_access('access archive') && $past_campaign_url) {
    $variables['archive_link'] = l(t('Newsletter Archive'), 'newsletter_archive');
  }
}

/* END TEMPLATE FUNCTIONS */

/* SOAP CALLS AND HELPERS */

/**
 * Check if the e-mail address is registrated as subscribed at campaign monitor
 * for the list ID parameter.
 *
 * @param string $api_key
 * @param int $list_id
 * @param string $email
 * @param boolean $show_errors
 * @return boolean, TRUE if e-mail is subscribed and FALSE if not.
 */
function _campaignmonitor_is_subscribed($api_key, $list_id, $email, $show_errors = FALSE) {
  $retval = FALSE;
  $cm = new CampaignMonitor($api_key, $client_id, $campaign_id, $list_id);
  $result = $cm
    ->subscribersGetIsSubscribed($email, $list_id);
  if (empty($result) || $result['anyType']['Code'] != 0) {
    if (empty($result)) {
      watchdog('campaignmonitor', 'There was a problem with the connection to Campaign Monitor.');
    }
    else {
      watchdog('campaignmonitor', 'Code - %code, Message - %message', array(
        '%code' => $result['anyType']['Code'],
        '%message' => $result['anyType']['Message'],
      ));
    }
    drupal_set_message(CM_ERROR, 'error', FALSE);
    $retval = FALSE;
  }
  elseif ($result['anyType'] == 'False') {
    $retval = FALSE;
  }
  elseif ($result['anyType'] == 'True') {
    $retval = TRUE;
  }
  return $retval;
}

/**
 * Subscribe a user to a newsletter list, by e-mail, name and custom fields.
 *
 * @param string $api_key
 * @param int $list_id
 * @param string $name
 * @param string $email
 * @param array $custom_fields
 * @param boolean $show_errors
 * @return boolean, TRUE if subscription succeeded else FALSE.
 *  */
function _campaignmonitor_add_subscriber($api_key, $list_id, $name, $email, $custom_fields = array(), $show_errors = FALSE) {
  $cm = new CampaignMonitor($api_key, $client_id, $campaign_id, $list_id);
  if (count($custom_fields) > 0) {
    $result = $cm
      ->subscriberAddAndResubscribeWithCustomFields($email, $name, $custom_fields);
  }
  else {
    $result = $cm
      ->subscriberAddAndResubscribe($email, $name);
  }
  if (empty($result) || $result['anyType']['Code'] != 0) {
    if (empty($result)) {
      watchdog('campaignmonitor', 'There was a problem with the connection to Campaign Monitor.');
    }
    else {
      watchdog('campaignmonitor', 'Code - %code, Message - %message', array(
        '%code' => $result['anyType']['Code'],
        '%message' => $result['anyType']['Message'],
      ));
    }
    drupal_set_message(CM_SUBSCRIPTION_ERROR, 'error', FALSE);
    return FALSE;
  }
  else {
    $details = _campaignmonitor_get_list_detail($api_key, $list_id);
    drupal_set_message(str_replace('%list', $details['Title'], CM_SUBSCRIPTION_SUCCESS), 'status');
    return TRUE;
  }
}

/**
 * Remove user form a newsletter list identified by e-mail and list ID.
 *
 * @param string $api_key
 * @param string $list_id
 * @param string $email
 * @param boolean $show_errors
 * @return boolean, TRUE if subscription removel succeeded else FALSE.
 */
function _campaignmonitor_remove_subscriber($api_key, $list_id, $email, $show_errors = FALSE) {
  $cm = new CampaignMonitor($api_key, $client_id, $campaign_id, $list_id);
  $result = $cm
    ->subscriberUnsubscribe($email);
  if (empty($result) || $result['Result']['Code'] == 0) {
    $details = _campaignmonitor_get_list_detail($api_key, $list_id);
    drupal_set_message(str_replace('%list', $details['Title'], CM_UNSUBSCRIPTION_SUCCESS), 'status');
    return TRUE;
  }
  else {
    if (empty($result)) {
      watchdog('campaignmonitor', 'There was a problem with the connection to Campaign Monitor.');
    }
    else {
      watchdog('campaignmonitor', 'Code - %code, Message - %message', array(
        '%code' => $result['anyType']['Code'],
        '%message' => $result['anyType']['Message'],
      ));
    }
    drupal_set_message(CM_UNSUBSCRIPTION_ERROR, 'error', FALSE);
    return FALSE;
  }
}

/**
 * Get information form campaign mointor about a subscribed user base on list ID
 * and e-mail.
 *
 * @param string $api_key
 * @param string $list_id
 * @param string $email
 * @param boolean $show_errors
 * @return mixed an array with information will be return.
 */
function _campaignmonitor_get_subscriber($api_key, $list_id, $email, $show_errors = FALSE) {
  $retval = array(
    "name" => '',
    "email" => $email,
  );
  $cm = new CampaignMonitor($api_key, $client_id, $campaign_id, $list_id);
  $result = $cm
    ->subscriberGetSingleSubscriber($list_id, $email);
  if (empty($result) || $result['anyType']['Code'] != 0) {
    if (empty($result)) {
      watchdog('campaignmonitor', 'There was a problem with the connection to Campaign Monitor.');
    }
    else {
      watchdog('campaignmonitor', 'Code - %code, Message - %message', array(
        '%code' => $result['anyType']['Code'],
        '%message' => $result['anyType']['Message'],
      ));
    }
    drupal_set_message(CM_ERROR, 'error', FALSE);
  }
  else {
    $retval['name'] = $result['anyType']['Name'];
    $custom_fields = array();
    $c = $result['anyType']['CustomFields']['SubscriberCustomField'];
    if (!empty($c['Key'])) {
      $custom_fields = array();
      $custom_fields[$c['Key']] = $c['Value'];
    }
    else {
      if (!empty($c)) {
        foreach ($c as $field) {
          if (!empty($custom_fields[$field['Key']])) {
            if (is_array($custom_fields[$field['Key']])) {
              $values = $custom_fields[$field['Key']];
            }
            else {
              $values = array();
              $values[] = $custom_fields[$field['Key']];
            }
            $values[] = $field['Value'];
            $custom_fields[$field['Key']] = $values;
          }
          else {
            $custom_fields[$field['Key']] = $field['Value'];
          }
        }
      }
    }
    $retval['CustomFields'] = $custom_fields;
  }
  return $retval;
}

/**
 * Get all lists from campaign monitor identified by client ID and API key.
 *
 * @param string $api_key
 * @param string $client_id
 * @return array off lists.
 */
function _campaignmonitor_get_lists($api_key, $client_id, $reset = FALSE) {
  static $data;
  if (!isset($data) || $reset) {
    if (!$reset && ($cache = cache_get('campaignmonitor_lists')) && !empty($cache->data)) {

      // Cache information found.
      $data = $cache->data;
    }
    else {
      $data = array();

      // Get lists from campaign monitor.
      $cm = new CampaignMonitor($api_key, $client_id, $campaign_id, $list_id);
      $result = $cm
        ->clientGetLists();
      if (empty($result) || $result['anyType']['Code'] != 0) {
        if (empty($result)) {
          watchdog('campaignmonitor', 'There was a problem with the connection to Campaign Monitor.');
        }
        else {
          watchdog('campaignmonitor', 'Get Lists: Code - %code, Message - %message', array(
            '%code' => $result['anyType']['Code'],
            '%message' => $result['anyType']['Message'],
          ));
        }
        drupal_set_message(CM_ERROR, 'error', FALSE);
      }
      else {
        if (!empty($result['anyType']['List'])) {
          $lists = $result['anyType']['List'];

          // If there is only one list.
          if (!empty($lists['ListID'])) {
            $data[$lists['ListID']] = $lists['Name'];
          }
          else {
            foreach ($lists as $list) {
              $data[$list['ListID']] = $list['Name'];
            }
          }
        }
      }

      // Save the lists in the cache.
      cache_set('campaignmonitor_lists', $data);
    }
  }
  return $data;
}

/**
 * Get detailed information about a campaign mointor list.
 *
 * @staticvar array $lists
 * @param string $api_key
 * @param string $list_id
 * @param boolean $reset
 * @return array with detailed list information.
 */
function _campaignmonitor_get_list_detail($api_key, $list_id, $reset = FALSE) {
  $get_data = FALSE;
  static $data;
  if (!isset($data) || !isset($data[$list_id]) || $reset) {
    if (!$reset && ($cache = cache_get('campaignmonitor_list_detail')) && !empty($cache->data)) {
      $data = $cache->data;
      if (!isset($data[$list_id])) {

        // Cache found, but no information about current list.
        $get_data = TRUE;
      }
    }
    else {

      // No cache found.
      $data = array();
      $get_data = TRUE;
    }
  }

  // Data was not found in the cache, so aske campaign monitor for it.
  if ($get_data) {
    $cm = new CampaignMonitor($api_key, $client_id, $campaign_id, $list_id);
    $result = $cm
      ->listGetDetail($list_id);
    if (empty($result) || $result['anyType']['Code'] != 0) {
      if (empty($result)) {
        watchdog('campaignmonitor', 'There was a problem with the connection to Campaign Monitor.');
      }
      else {
        watchdog('campaignmonitor', 'Get List Detail: Code - %code, Message - %message', array(
          '%code' => $result['anyType']['Code'],
          '%message' => $result['anyType']['Message'],
        ));
      }
      drupal_set_message(CM_ERROR, 'error', FALSE);
    }
    else {

      // Save list details in the cache.
      $data[$list_id] = $result['anyType'];
      cache_set('campaignmonitor_list_detail', $data);
    }
  }
  return $data[$list_id];
}

/**
 * Get custom fields for a list.
 *
 * @param string $api_key
 * @param string $list_id
 * @return array custom field description
 */
function _campaignmonitor_get_custom_fields($api_key, $list_id, $reset = FALSE) {
  $get_data = FALSE;
  static $data;
  if (!isset($data) || !isset($data[$list_id]) || $reset) {
    if (!$reset && ($cache = cache_get('campaignmonitor_custom_fields')) && !empty($cache->data)) {
      $data = $cache->data;
      if (!isset($data[$list_id])) {

        // Cache found, but no information about current list.
        $get_data = TRUE;
      }
    }
    else {

      // No cache found.
      $data = array();
      $get_data = TRUE;
    }
  }
  if ($get_data) {
    $retval = array();
    $cm = new CampaignMonitor($api_key, $client_id, $campaign_id, $list_id);
    $result = $cm
      ->listGetCustomFields($list_id);
    if (empty($result) && !is_array($result) || $result['anyType']['Code'] != 0) {
      if (empty($result)) {
        watchdog('campaignmonitor', 'There was a problem with the connection to Campaign Monitor.');
      }
      else {
        watchdog('campaignmonitor', 'Get Custom Fields: Code - %code, Message - %message', array(
          '%code' => $result['anyType']['Code'],
          '%message' => $result['anyType']['Message'],
        ));
      }
      drupal_set_message(CM_ERROR, 'error', FALSE);
    }
    else {
      if (!empty($result['anyType']['ListCustomField'])) {

        // If there is only one list.
        if (!empty($result['anyType']['ListCustomField']['FieldName'])) {
          $retval[] = $result['anyType']['ListCustomField'];
        }
        else {
          $retval = $result['anyType']['ListCustomField'];
        }
      }

      // Save list details in the cache.
      $data[$list_id] = $retval;
      cache_set('campaignmonitor_custom_fields', $data);
    }
  }
  return $data[$list_id];
}

Functions

Namesort descending Description
campaignmonitor_block Implementation of hook_block().
campaignmonitor_block_list Returns a list of blocks in a form suitable for hook_block() when $op == list: A block is returned for each CampaignMonitor list chosen in admin settings
campaignmonitor_campaignmonitor_field_keys Implementation of hook_campaignmonitor_field_keys
campaignmonitor_campaignmonitor_field_key_values Implementation of hook_campaignmonitor_field_key_values
campaignmonitor_form_alter Implementation of hook_form_alter().
campaignmonitor_get_available_lists
campaignmonitor_get_field_keys Get the available field keys
campaignmonitor_get_field_key_values Get all the potential merge var values for a given user
campaignmonitor_help Implementation of hook_help().
campaignmonitor_menu Implementation of hook_menu().
campaignmonitor_newsletter_archive
campaignmonitor_perm Implementation of hook_perm().
campaignmonitor_subscribe_form
campaignmonitor_subscribe_form_submit
campaignmonitor_theme Implementation of hook_theme().
campaignmonitor_user_page_access Access callback for the user newsletters page.
template_preprocess_campaignmonitor_block_content Implementation of preprocess_campaignmontor_block_content(). Which adds a newsletter archive link, if the archive URL is defined and user access is granted.
_campaignmonitor_add_subscriber Subscribe a user to a newsletter list, by e-mail, name and custom fields.
_campaignmonitor_altered_form_submit
_campaignmonitor_get_custom_fields Get custom fields for a list.
_campaignmonitor_get_lists Get all lists from campaign monitor identified by client ID and API key.
_campaignmonitor_get_list_detail Get detailed information about a campaign mointor list.
_campaignmonitor_get_subscriber Get information form campaign mointor about a subscribed user base on list ID and e-mail.
_campaignmonitor_get_user_tokens Get the user tokens for merging
_campaignmonitor_is_subscribed Check if the e-mail address is registrated as subscribed at campaign monitor for the list ID parameter.
_campaignmonitor_remove_subscriber Remove user form a newsletter list identified by e-mail and list ID.

Constants