You are here

campaignmonitor.module in Campaign Monitor 5.2

File

campaignmonitor.module
View source
<?php

/**
 * @file
 * Campaign Monitor integration.
 *
 * Campaign Monitor is a newsletter/subscriber list system.
 * 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/
 */
@(require_once drupal_get_path('module', 'campaignmonitor') . '/lib/CMBase.php');

/******************************
 DRUPAL HOOKS
******************************/

/**
 * Implementation of hook_help()
 */
function campaignmonitor_help($section) {
  switch ($section) {
    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($may_cache) {
  global $user;
  $items = array();
  if ($may_cache) {
    $items[] = array(
      'path' => 'admin/settings/campaignmonitor',
      'title' => t('Campaign Monitor'),
      'description' => t('Setup Campaign Monitor values.'),
      'callback' => 'drupal_get_form',
      'callback arguments' => 'campaignmonitor_admin',
      'access' => user_access('administer campaignmonitor'),
      'type' => MENU_NORMAL_ITEM,
    );
    $items[] = array(
      'path' => 'newsletter_archive',
      'title' => t('Newsletter Archive'),
      'callback' => 'campaignmonitor_newsletter_archive',
      'access' => user_access('access archive'),
      'type' => MENU_SUGGESTED_ITEM,
    );
  }
  else {
    if (arg(0) == 'user' && is_numeric(arg(1))) {
      $account = user_load(array(
        'uid' => arg(1),
      ));
      if ($user->uid == $account->uid || user_access('administer users')) {
        $items[] = array(
          'path' => 'user/' . arg(1) . '/newsletters',
          'title' => t('My Newsletters'),
          'callback' => 'campaignmonitor_user_page',
          'type' => MENU_LOCAL_TASK,
          'access' => user_access('join newsletter'),
          'weight' => 5,
        );
      }
    }
  }
  return $items;
}

/**
 * Implementation of hook_form_alter()
 */
function campaignmonitor_form_alter($form_id, &$form) {
  $display_on = variable_get('campaignmonitor_display_on', array());
  if (('contact_mail_page' == $form_id && $display_on['contact'] || 'user_register' == $form_id && $display_on['registration']) && user_access('join newsletter')) {
    $form['subscribe_newsletter'] = array(
      '#type' => 'checkbox',
      '#title' => t(variable_get('campaignmonitor_checkboxdisplaytext', 'Join our Newsletter?')),
      '#weight' => 99,
      '#default_value' => 0,
    );
    $form['submit']['#weight'] = 100;
    $form['#submit'] = array(
      'campaignmonitor_form_submit' => array(),
    ) + (array) $form['#submit'];
  }
}

/**
 * Implementation of hook_block()
 */
function campaignmonitor_block($op = 'list', $delta = 0, $edit = array()) {
  if ($op == 'list') {
    $blocks[0] = array(
      'info' => t('Newsletter block to allow signup to newsletter for all.'),
      'weight' => 0,
      'enabled' => 0,
      'region' => 'left',
    );
    return $blocks;
  }
  else {
    if ($op == 'configure' && $delta == 0) {

      /* $form['items'] = array(
           '#type' => 'select',
           '#title' => t('Number of items'),
           '#default_value' => variable_get('XXX_block_items', 0),
           '#options' => array('1', '2', '3'),
         );
         return $form;*/
    }
    else {
      if ($op == 'save' && $delta == 0) {

        /* variable_set('XXX_block_items', $edit['items']);*/
      }
      else {
        if ($op == 'view') {
          switch ($delta) {
            case 0:
              $block = array(
                'subject' => t('Join Newsletter'),
                'content' => campaignmonitor_signup_block(),
              );
              break;
          }
          return $block;
        }
      }
    }
  }
}

/*** END DRUPAL HOOKS ***/

/******************************
 MODULE FUNCTIONS
******************************/
function campaignmonitor_admin() {
  $form['campaignmonitor_api_key'] = array(
    '#type' => 'textfield',
    '#title' => t('API Key'),
    '#default_value' => variable_get('campaignmonitor_api_key', ''),
    '#required' => TRUE,
    '#size' => 50,
    '#maxlength' => 200,
    '#description' => t("Your Campaign Monitor API Key."),
  );
  $form['campaignmonitor_client_id'] = array(
    '#type' => 'textfield',
    '#title' => t('Client ID'),
    '#default_value' => variable_get('campaignmonitor_client_id', ''),
    '#required' => TRUE,
    '#size' => 50,
    '#maxlength' => 200,
    '#description' => t("Your Campaign Monitor Client ID."),
  );
  $form['campaignmonitor_list_id'] = array(
    '#type' => 'textfield',
    '#title' => t('List ID'),
    '#default_value' => variable_get('campaignmonitor_list_id', ''),
    '#required' => TRUE,
    '#size' => 50,
    '#maxlength' => 200,
    '#description' => t("Your Campaign Monitor List ID."),
  );
  $form['campaignmonitor_display_on'] = array(
    '#type' => 'checkboxes',
    '#title' => t('Display on Options'),
    '#default_value' => variable_get('campaignmonitor_display_on', array()),
    '#options' => array(
      'contact' => t('Contact Page'),
      'registration' => t('Registration Page'),
    ),
    '#description' => t('Choose which forms you want to display the Join Newsletter checkbox.'),
  );
  $form['campaignmonitor_checkboxdisplaytext'] = array(
    '#type' => 'textfield',
    '#title' => t('Display Text for Checkbox'),
    '#default_value' => variable_get('campaignmonitor_checkboxdisplaytext', 'Join our Newsletter?'),
    '#description' => t("This text will display next to the checkbox on the selected forms."),
  );
  $form['campaignmonitor_userpagedisplaytext'] = array(
    '#type' => 'textfield',
    '#title' => t('Display Text for User Page'),
    '#default_value' => variable_get('campaignmonitor_userpagedisplaytext', 'Newsletter'),
    '#description' => t("This text will display next to the checkbox on the user profile page."),
  );
  $form['campaignmonitor_pastcampaignurl'] = array(
    '#type' => 'textfield',
    '#title' => t('Past Campaign URL'),
    '#default_value' => variable_get('campaignmonitor_pastcampaignurl', ''),
    '#size' => 100,
    '#maxlength' => 100,
    '#description' => t("This is required if you want to use the page that displays past campaigns. You can find this value if you go to Manage Clients, click on the client, go to the link that tells you how to display past campaigns, then copy the URL ONLY from the html given. The URL is in between the src=\"\" value."),
  );
  $form['campaignmonitor_connection_timeout'] = array(
    '#type' => 'textfield',
    '#title' => t('Connection timeout'),
    '#default_value' => variable_get('campaignmonitor_connection_timeout', 15),
    '#size' => 10,
    '#maxlength' => 10,
    '#description' => t("If your server can't get through to the API, or the API server is down, this is the amount of time until the connection times out in seconds. Default is 15 seconds."),
  );
  return system_settings_form($form);
}
function campaignmonitor_signup_block() {
  global $user;
  $content = '';
  $content .= drupal_get_form('campaignmonitor_general_form');
  if (user_access('access archive')) {
    $content .= l('Newsletter Archive', 'newsletter_archive');
  }
  return $content;
}
function campaignmonitor_user_page() {
  return drupal_get_form('campaignmonitor_user_form');
}
function campaignmonitor_user_form() {
  global $user;

  // Replace api_key and list_id with your own details
  $api_key = variable_get('campaignmonitor_api_key', '');
  $list_id = variable_get('campaignmonitor_list_id', '');
  $email = $user->mail;
  if (_campaignmonitor_is_subscribed($api_key, $list_id, $email, TRUE)) {
    $default = TRUE;
  }
  else {
    $default = FALSE;
  }
  $form['subscribe_newsletter'] = array(
    '#type' => 'checkbox',
    '#title' => variable_get('campaignmonitor_userpagedisplaytext', 'Newsletter'),
    '#default_value' => $default,
  );
  $form['is_subscribed'] = array(
    '#type' => 'hidden',
    '#default_value' => $default,
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Save'),
  );
  return $form;
}
function campaignmonitor_newsletter_archive() {
  $url = variable_get('campaignmonitor_pastcampaignurl', '');
  if ($url == '') {
    $content = '<p>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('campaignmonitor_pastcampaignurl', '') . '"></script>';
  }
  return $content;
}
function campaignmonitor_user_form_submit($form_id, $form_values) {
  global $user;

  // Check if the profile module is installed. If it is, use the name element of the profile
  if (module_exists("profile")) {
    profile_load_profile($user);
    $profile_name = $user->profile_name;
  }

  // Replace api_key and list_id with your own details
  $api_key = variable_get('campaignmonitor_api_key', '');
  $list_id = variable_get('campaignmonitor_list_id', '');
  $name = $profile_name;
  $email = $user->mail;

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

    // this is the case where they now want to be subscribed, and weren't before
    _campaignmonitor_add_subscriber($api_key, $list_id, $name, $email);
  }
  else {
    if (!$form_values['subscribe_newsletter'] && $form_values['is_subscribed']) {

      // 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_general_form() {
  global $user;
  $name = '';
  $email = '';
  $default = FALSE;

  // Check if the profile module is installed. If it is, use the name element of the profile
  if (module_exists("profile")) {
    profile_load_profile($user);
    $name = $user->profile_name;
  }
  if ($user->uid != 0) {
    $email = $user->mail;
    if (_campaignmonitor_is_subscribed(variable_get('campaignmonitor_api_key', ''), variable_get('campaignmonitor_list_id', ''), $email)) {
      $default = TRUE;

      // Also if subscribed get name
      $subscriber = _campaignmonitor_get_subscriber(variable_get('campaignmonitor_api_key', ''), variable_get('campaignmonitor_list_id', ''), $email);
      $name = $subscriber['name'];
    }
    else {
      $default = FALSE;
    }
  }
  $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,
  );
  $form['unsubscribe_newsletter'] = array(
    '#type' => 'checkbox',
    '#title' => t('Unsubscribe'),
    '#default_value' => $default,
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  );
  return $form;
}
function campaignmonitor_general_form_submit($form_id, $form_values) {

  // Replace api_key and list_id with your own details
  $api_key = variable_get('campaignmonitor_api_key', '');
  $list_id = variable_get('campaignmonitor_list_id', '');
  $name = $form_values['name'];
  $email = $form_values['email'];

  // 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
    _campaignmonitor_add_subscriber($api_key, $list_id, $name, $email);
  }
  else {
    if ($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_form_submit($form_id, $form_values) {
  if ($form_values['subscribe_newsletter']) {
    if ('contact_mail_page' == $form_id) {
      $form_values['message'] .= "\n\n" . t('Subscribed to newsletter.');
    }

    // Replace api_key and list_id with your own details
    $api_key = variable_get('campaignmonitor_api_key', '');
    $list_id = variable_get('campaignmonitor_list_id', '');
    $email = $form_values['mail'];
    $name = $form_values['name'];
    _campaignmonitor_add_subscriber($api_key, $list_id, $name, $email);
  }
}

/*** END MODULE FUNCTIONS ***/

/******************************
 SOAP CALLS AND HELPERS
******************************/
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 ($result['anyType']['Code'] != 0) {
    watchdog('campaignmonitor', 'Code - ' . $result['anyType']['Code'] . ', Message - ' . $result['anyType']['Message'], WATCHDOG_ERROR);
    $retval = FALSE;
    if ($show_errors) {
      drupal_set_message("There is an error with the newsletter server. Please try again later.", 'error');
    }
  }
  else {
    if ($result['anyType'] == 'False') {
      $retval = FALSE;
    }
    else {
      if ($result['anyType'] == 'True') {
        $retval = TRUE;
      }
    }
  }
  return $retval;
}
function _campaignmonitor_add_subscriber($api_key, $list_id, $name, $email, $show_errors = FALSE) {
  $cm = new CampaignMonitor($api_key, $client_id, $campaign_id, $list_id);
  $result = $cm
    ->subscriberAddAndResubscribe($email, $name);
  if ($result['anyType']['Code'] != 0) {
    watchdog('campaignmonitor', 'Code - ' . $result['anyType']['Code'] . ', Message - ' . $result['anyType']['Message'], WATCHDOG_ERROR);
    drupal_set_message("There was an error joining to newsletter.", 'error');
  }
  else {
    drupal_set_message("You have successfully been added.", 'status');
  }
}
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 ($result['Result']['Code'] == 0) {
    drupal_set_message("You have successfully been unsubscribed.", 'status');
  }
  else {
    watchdog('campaignmonitor', 'Code - ' . $result['anyType']['Code'] . ', Message - ' . $result['anyType']['Message'], WATCHDOG_ERROR);
    drupal_set_message("There was an error unsubscribing from newsletter.", 'error');
  }
}
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
    ->makeCall('Subscribers.GetSingleSubscriber', array(
    'params' => array(
      'ListID' => $list_id,
      'EmailAddress' => $email,
    ),
  ));
  if ($result['anyType']['Code'] != 0) {
    watchdog('campaignmonitor', 'Code - ' . $result['anyType']['Code'] . ', Message - ' . $result['anyType']['Message'], WATCHDOG_ERROR);
    if ($show_errors) {
      drupal_set_message("There is an error with the newsletter server. Please try again later.", 'error');
    }
  }
  else {
    $retval['name'] = $result['anyType']['Name'];
  }
  return $retval;
}

/*** END SOAP CALLS AND HELPERS ***/