You are here

campaignmonitor.module in Campaign Monitor 7

Module that plugs in Campaign Monitor functionality to your Drupal web site.

For Campaign Monitor information see: http://www.campaignmonitor.com/.

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/.
 */
define('CAMPAIGNMONITOR_ARCHIVE_DELTA', 'HASHc32bde51684d37a36679301a1e9');

/**
 * Implements 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>';
  }
}

/**
 * Implements hook_perm().
 */
function campaignmonitor_permission() {
  return array(
    'administer campaignmonitor' => array(
      'title' => t('Administer Campaign Monitor'),
      'description' => t('Administer Campaign Monitor settings.'),
    ),
    'access archive' => array(
      'title' => t('Access newsletter archive'),
      'description' => t('Access newsletter achive'),
    ),
    'join newsletter' => array(
      'title' => t('Join newsletters'),
      'description' => t('Join newsletters'),
    ),
  );
}

/**
 * Implements hook_menu().
 */
function campaignmonitor_menu() {
  $items = array();
  $items['admin/config/services/campaignmonitor'] = array(
    'title' => 'Campaign Monitor',
    'description' => 'General Campaign Monitor settings.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array(
      'campaignmonitor_admin_settings_general',
    ),
    'access arguments' => array(
      'administer campaignmonitor',
    ),
    'type' => MENU_NORMAL_ITEM,
    'file' => 'includes/campaignmonitor.admin.inc',
  );
  $items['admin/config/services/campaignmonitor/general'] = array(
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'title' => 'General',
    'weight' => -50,
  );
  $items['admin/config/services/campaignmonitor/lists'] = array(
    'title' => 'Lists',
    'page callback' => 'campaignmonitor_admin_settings_lists',
    'access arguments' => array(
      'administer campaignmonitor',
    ),
    'weight' => -40,
    'type' => MENU_LOCAL_TASK,
    'file' => 'includes/campaignmonitor_lists.admin.inc',
  );
  $items['admin/config/services/campaignmonitor/lists/add'] = array(
    'title' => 'Add list',
    'page callback' => 'drupal_get_form',
    'page arguments' => array(
      'campaignmonitor_admin_settings_list_create_form',
    ),
    'access arguments' => array(
      'administer campaignmonitor',
    ),
    'type' => MENU_LOCAL_ACTION,
    'file' => 'includes/campaignmonitor_lists.admin.inc',
  );
  $items['admin/config/services/campaignmonitor/lists/%/edit'] = array(
    'title' => 'Edit list',
    'page callback' => 'drupal_get_form',
    'page arguments' => array(
      'campaignmonitor_admin_settings_list_edit',
      5,
    ),
    'access arguments' => array(
      'administer campaignmonitor',
    ),
    'type' => MENU_CALLBACK,
    'file' => 'includes/campaignmonitor_lists.admin.inc',
  );
  $items['admin/config/services/campaignmonitor/lists/%/delete'] = array(
    'title' => 'Edit list',
    'page callback' => 'drupal_get_form',
    'page arguments' => array(
      'campaignmonitor_admin_settings_list_delete',
      5,
    ),
    'access arguments' => array(
      'administer campaignmonitor',
    ),
    'type' => MENU_CALLBACK,
    'file' => 'includes/campaignmonitor_lists.admin.inc',
  );
  $items['admin/config/services/campaignmonitor/lists/%/enable'] = array(
    'title' => 'Enable list',
    'page callback' => 'campaignmonitor_admin_settings_list_enable',
    'page arguments' => array(
      5,
    ),
    'access arguments' => array(
      'administer campaignmonitor',
    ),
    'type' => MENU_CALLBACK,
    'file' => 'includes/campaignmonitor_lists.admin.inc',
  );
  $items['admin/config/services/campaignmonitor/lists/%/disable'] = array(
    'title' => 'Disable list',
    'page callback' => 'campaignmonitor_admin_settings_list_disable',
    'page arguments' => array(
      5,
    ),
    'access arguments' => array(
      'administer campaignmonitor',
    ),
    'type' => MENU_CALLBACK,
    'file' => 'includes/campaignmonitor_lists.admin.inc',
  );
  $items['admin/config/services/campaignmonitor/states'] = array(
    'title' => 'Statistics',
    'page callback' => 'campaignmonitor_admin_settings_stats',
    'access arguments' => array(
      'administer campaignmonitor',
    ),
    'weight' => -30,
    'type' => MENU_LOCAL_TASK,
    'file' => 'includes/campaignmonitor_stats.admin.inc',
  );
  return $items;
}

/**
 * Implements hook_theme().
 */
function campaignmonitor_theme() {
  return array(
    'campaignmonitor_subscribe_form' => array(
      'render element' => 'form',
    ),
    'campaignmonitor_list_stats' => array(
      'template' => 'campaignmonitor_list_stats',
      'variables' => array(
        'list' => NULL,
        'stats' => NULL,
      ),
      'file' => 'includes/campaignmonitor_stats.admin.inc',
    ),
  );
}

/**
 * Implements hook_block_info().
 */
function campaignmonitor_block_info() {
  $blocks = array();
  $account = variable_get('campaignmonitor_account', FALSE);
  if ($account) {

    // Create a block for each list.
    $lists = CampaignMonitor::getConnector()
      ->getLists();
    if ($lists) {
      foreach ($lists as $list_id => $list) {

        // Get local configuration options and check if the list is enabled.
        if (campaignmonitor_is_list_enabled($list_id)) {
          $blocks[$list_id] = array(
            'info' => t('Subscribe to @list_name (Campaign Monitor)', array(
              '@list_name' => $list['name'],
            )),
          );
        }
      }
    }
    $settings = variable_get('campaignmonitor_general', FALSE);
    if ($settings && isset($settings['archive'])) {
      $blocks[CAMPAIGNMONITOR_ARCHIVE_DELTA] = array(
        'info' => t('Campaign monitor newsletter archive'),
      );
    }
  }
  return $blocks;
}

/**
 * Implements hook_block_view().
 */
function campaignmonitor_block_view($delta) {
  $block = array();
  if (CAMPAIGNMONITOR_ARCHIVE_DELTA == $delta) {

    // Connect to Campaign Monitor and get past campaigns.
    $campaigns = CampaignMonitor::getConnector()
      ->getCampaigns();
    if ($campaigns) {
      $content = '<ul>';
      foreach ($campaigns as $campaign) {
        $content .= '<li>' . l($campaign['Name'], $campaign['Link']) . ' ' . format_date($campaign['Sent'], 'short') . '</li>';
      }
      $content .= '</ul>';

      // Build block.
      $block['subject'] = t('Newsletter archive');
      $block['content'] = array(
        '#markup' => $content,
      );
    }
    else {
      drupal_set_message(t('Unable to fetch campaigns from Campaign monitor.'), 'error');
    }
  }
  else {

    // Get lists form Campaign Monitor.
    $lists = CampaignMonitor::getConnector()
      ->getLists();
    if ($lists) {
      $block['subject'] = t('%name', array(
        '%name' => $lists[$delta]['name'],
      ));
      if (campaignmonitor_is_list_enabled($delta)) {
        $block['content'] = drupal_get_form('campaignmonitor_subscribe_form', $delta);
      }
      else {
        $block['content'] = t('The Campaign monitor list "@list" is not enabled.', array(
          '@list' => $lists[$delta]['name'],
        ));
      }

      // Add some basic styling of form elements.
      drupal_add_css(drupal_get_path('module', 'campaignmonitor') . '/css/campaignmonitor.theme.css');
    }
    else {
      drupal_set_message(t('Unable to fetch lists from Campaign monitor.'), 'error');
    }
  }
  return $block;
}

/**
 * Builds the subscription form used in blocks.
 */
function campaignmonitor_subscribe_form($form, &$form_state, $list_id) {
  global $user;

  // Get Campaign Monitor object.
  $cm = CampaignMonitor::getConnector();

  // Get lists from Campaign Monitor (or the local cache).
  $list = $cm
    ->getExtendedList($list_id);
  $list_options = variable_get('campaignmonitor_list_' . $list_id, array());

  // Set options for the form.
  $form = array(
    '#tree' => TRUE,
    '#attributes' => array(
      'class' => array(
        'campaignmonitor-subscribe-form',
        'campaignmonitor-subscribe-form-' . str_replace(' ', '-', drupal_strtolower($list['name'])),
      ),
    ),
  );

  // Try to get the e-mail address from the user object.
  if ($user->uid != 0) {
    $email = $user->mail;
  }

  // Should the name field be displayed for this user.
  if (isset($list_options['display']['name']) && $list_options['display']['name']) {

    // Token replace if the token module is present.
    if (isset($list_options['tokens']['name']) && module_exists('token') && $user->uid != 0) {
      $name = token_replace($list_options['tokens']['name'], array(), array(
        'clear' => TRUE,
      ));
    }

    // Check if the user is subscribed and get name from Campaign Monitor.
    if (!empty($email) && $cm
      ->isSubscribed($list_id, $email)) {

      // If subscribed, get name from Campaign Monitor.
      $subscriber = $cm
        ->getSubscriber($list_id, $email);
      $name = isset($subscriber['Name']) ? $subscriber['Name'] : $name;
    }
    $form['name'] = array(
      '#type' => 'textfield',
      '#title' => t('Name'),
      '#required' => TRUE,
      '#maxlength' => 200,
      '#default_value' => isset($name) ? $name : '',
    );
  }
  $form['email'] = array(
    '#type' => 'textfield',
    '#title' => t('Email'),
    '#required' => TRUE,
    '#maxlength' => 200,
    '#default_value' => isset($email) ? $email : '',
    '#element_validate' => array(
      'campaignmonitor_email_element_validate',
    ),
  );
  foreach ($list['CustomFields'] as $key => $field) {

    // Form API can't handle keys with [] in all cases.
    $form_key = str_replace(array(
      '[',
      ']',
    ), '', $key);

    // Check if field should be displayed.
    if (!isset($list_options['CustomFields']['selected'][$form_key]) || !$list_options['CustomFields']['selected'][$form_key]) {

      // Field is not selected, so continue.
      continue;
    }

    // Token replace default value, if the token module is present.
    $token = '';
    if (module_exists('token') && isset($list_options['tokens'][$form_key])) {
      $token = token_replace($list_options['tokens'][$form_key]);
    }
    switch ($field['DataType']) {
      case 'Text':
        $form['CustomFields'][$form_key] = array(
          '#type' => 'textfield',
          '#title' => check_plain($field['FieldName']),
          '#maxlength' => 200,
          '#default_value' => isset($subscriber['CustomFields'][$field['FieldName']]) ? $subscriber['CustomFields'][$field['FieldName']] : $token,
        );
        break;
      case 'MultiSelectOne':
        $options = array();
        foreach ($field['FieldOptions'] as $option) {
          $options[$option] = $option;
        }
        $form['CustomFields'][$form_key] = array(
          '#type' => 'select',
          '#title' => check_plain($field['FieldName']),
          '#options' => $options,
          '#default_value' => isset($subscriber['CustomFields'][$field['FieldName']]) ? $subscriber['CustomFields'][$field['FieldName']] : $token,
        );
        break;
      case 'MultiSelectMany':
        $options = array();
        foreach ($field['FieldOptions'] as $option) {
          $options[$option] = $option;
        }

        // If one value was selected, default is a string else an array.
        $cm_default = isset($subscriber['CustomFields'][$field['FieldName']]) ? $subscriber['CustomFields'][$field['FieldName']] : array();
        $is_array = is_array($cm_default);
        $default = array();
        foreach ($options as $value) {
          if ($is_array) {
            if (in_array($value, $cm_default)) {
              $default[$value] = $value;
            }
          }
          elseif ($cm_default == $value) {
            $default[$cm_default] = $cm_default;
          }
          else {
            $default[$value] = 0;
          }
        }
        $form['CustomFields'][$form_key] = array(
          '#type' => 'checkboxes',
          '#title' => check_plain($field['FieldName']),
          '#options' => $options,
          '#default_value' => $default,
        );
        break;
      case 'Number':
        $form['CustomFields'][$form_key] = array(
          '#type' => 'textfield',
          '#title' => check_plain($field['FieldName']),
          '#default_value' => isset($subscriber['CustomFields'][$field['FieldName']]) ? $subscriber['CustomFields'][$field['FieldName']] : $token,
        );
        break;
      case 'Date':

        // Load jQuery datepicker to ensure the right date format.
        drupal_add_library('system', 'ui.datepicker');
        $form['CustomFields'][$form_key] = array(
          '#type' => 'textfield',
          '#title' => check_plain($field['FieldName']),
          '#default_value' => isset($subscriber['CustomFields'][$field['FieldName']]) ? $subscriber['CustomFields'][$field['FieldName']] : $token,
          '#attributes' => array(
            'class' => array(
              'campaignmonitor-date',
            ),
          ),
          '#attached' => array(
            'js' => array(
              'type' => 'file',
              'data' => drupal_get_path('module', 'campaignmonitor') . '/js/campaignmonitor.js',
            ),
          ),
        );
        break;
    }
  }
  $form['list_id'] = array(
    '#type' => 'hidden',
    '#default_value' => $list_id,
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Subscribe'),
  );
  return $form;
}

/**
 * Form element validation handler for the subscribe email field.
 */
function campaignmonitor_email_element_validate($element, &$form_state) {
  $value = $element['#value'];
  if ($value !== '' && !valid_email_address($value)) {
    form_error($element, t('%name must be a valid email address.', array(
      '%name' => $element['#title'],
    )));
  }
}

/**
 * Subscribe form submit handler.
 */
function campaignmonitor_subscribe_form_submit($form, &$form_state) {

  // Get a Campaign Monitor object.
  $cm = CampaignMonitor::getConnector();
  $custom_fields = array();
  if (isset($form_state['values']['CustomFields'])) {
    foreach ($form_state['values']['CustomFields'] as $key => $field) {
      if (is_array($field)) {

        // Filter out non-selected values.
        $field = array_filter($field);

        // Transform two level array into one level.
        foreach ($field as $value) {
          $custom_fields[] = array(
            'Key' => check_plain($key),
            'Value' => check_plain($value),
          );
        }
      }
      else {

        // Add non-array custom fields.
        $custom_fields[] = array(
          'Key' => check_plain($key),
          'Value' => check_plain($field),
        );
      }
    }
  }
  $list_id = $form_state['values']['list_id'];
  $name = isset($form_state['values']['name']) ? check_plain($form_state['values']['name']) : '';
  $email = check_plain($form_state['values']['email']);

  // Update subscriber information or add new subscriber to the list.
  if (!$cm
    ->subscribe($list_id, $email, $name, $custom_fields)) {
    form_set_error('', t('You were not subscribed to the list, please try again.'));
    $form_state['redirect'] = FALSE;
    return FALSE;
  }

  // Check if the user should be sent to a subscribe page.
  $lists = $cm
    ->getLists();
  if (isset($lists[$list_id]['details']['ConfirmationSuccessPage']) && !empty($lists[$list_id]['details']['ConfirmationSuccessPage'])) {
    drupal_goto($lists[$list_id]['details']['ConfirmationSuccessPage']);
  }
  else {
    drupal_set_message(t('You are now subscribed to the "@list" list.', array(
      '@list' => $lists[$list_id]['name'],
    )), 'status');
  }
}

/**
 * Checks if the list given by id is enabled locally.
 *
 * If the list id enabled 1 is returned else 0.
 *
 * @param string $list_id
 *   The Campaign Monitor list ID.
 *
 * @return int
 *   1 if list is enabled, 0 otherwise.
 */
function campaignmonitor_is_list_enabled($list_id) {
  $list_options = variable_get('campaignmonitor_list_' . $list_id, FALSE);
  return isset($list_options['status']['enabled']) ? $list_options['status']['enabled'] : 1;
}

Functions

Namesort descending Description
campaignmonitor_block_info Implements hook_block_info().
campaignmonitor_block_view Implements hook_block_view().
campaignmonitor_email_element_validate Form element validation handler for the subscribe email field.
campaignmonitor_help Implements hook_help().
campaignmonitor_is_list_enabled Checks if the list given by id is enabled locally.
campaignmonitor_menu Implements hook_menu().
campaignmonitor_permission Implements hook_perm().
campaignmonitor_subscribe_form Builds the subscription form used in blocks.
campaignmonitor_subscribe_form_submit Subscribe form submit handler.
campaignmonitor_theme Implements hook_theme().

Constants

Namesort descending Description
CAMPAIGNMONITOR_ARCHIVE_DELTA @file Module that plugs in Campaign Monitor functionality to your Drupal web site.