You are here

campaignmonitor_user.module in Campaign Monitor 7

Same filename and directory in other branches
  1. 8 modules/campaignmonitor_user/campaignmonitor_user.module

Tab to the profile page to select newsletters to subscribe to.

File

modules/campaignmonitor_user/campaignmonitor_user.module
View source
<?php

/**
 * @file
 * Tab to the profile page to select newsletters to subscribe to.
 */

/**
 * Implements hook_perm().
 */
function campaignmonitor_user_permission() {
  return [
    'access campaign monitor user' => [
      'title' => t('Access Campaign Monitor on user page'),
      'description' => t('Allow user to subscribe to lists on the user page.'),
    ],
  ];
}

/**
 * Implements hook_menu().
 */
function campaignmonitor_user_menu() {
  $items = [];
  $items['user/%user/newsletters'] = [
    'title' => 'My newsletters',
    'page callback' => 'drupal_get_form',
    'page arguments' => [
      'campaignmonitor_user_form',
    ],
    'access callback' => 'campaignmonitor_user_access',
    'access arguments' => [
      1,
    ],
    'type' => MENU_LOCAL_TASK,
    'weight' => 5,
  ];
  return $items;
}

/**
 * Access callback for the user newsletters page.
 */
function campaignmonitor_user_access($account) {
  global $user;
  if ($user->uid && $user->uid == $account->uid && user_access('access campaign monitor user')) {
    return TRUE;
  }
  return FALSE;
}

/**
 * Builds the selection list for the user profile page.
 */
function campaignmonitor_user_form() {
  global $user;
  $form = [];

  // Get connected to the API and get lists.
  $cm = CampaignMonitor::getConnector();
  $lists = $cm
    ->getLists();

  // Build options for the form selector.
  $options = [];
  $default = [];
  foreach ($lists as $list_id => $list) {

    // Check if the list is selected to be shown.
    $list_options = variable_get('campaignmonitor_list_' . $list_id, []);
    if (campaignmonitor_is_list_enabled($list_id) && isset($list_options['display']['user']) && $list_options['display']['user']) {
      $options[$list_id] = $list['name'];

      // Check if the user is subscribed to the current list.
      $default[$list_id] = 0;
      if ($cm
        ->isSubscribed($list_id, $user->mail)) {
        $default[$list_id] = $list_id;
      }
    }
  }
  $defaults = variable_get('campaignmonitor_general', []);
  if (!empty($options)) {
    $form['lists'] = [
      '#type' => 'checkboxes',
      '#title' => t('News lists'),
      '#description' => !empty($defaults['instructions']) ? t('%instructions', [
        '%instructions' => $defaults['instructions'],
      ]) : t('Select the news lists that you want to subscribe to.'),
      '#options' => $options,
      '#default_value' => $default,
    ];
    $form['submit'] = [
      '#type' => 'submit',
      '#value' => t('Update subscriptions'),
    ];
  }
  else {
    drupal_set_message(t('There are no available lists to subscribe to at the moment.'), 'warning');
  }
  $form['#submit'][] = 'campaignmonitor_user_form_submit';
  return $form;
}

/**
 * Submission form handler.
 *
 * The information about the selected list will be
 * submitted to Campaign Monitor.
 */
function campaignmonitor_user_form_submit($form, &$form_state) {
  global $user;

  // Get connected to the API and get lists.
  $cm = CampaignMonitor::getConnector();
  $lists_info = $cm
    ->getLists();

  // Loop through the lists.
  foreach ($form_state['values']['lists'] as $list_id => $selected) {
    if ($selected) {

      // If not subscribed, subscribe, else do nothing. The subscribe state is
      // already in the cache, so it cheaper to check then re-subscribe.
      if (!$cm
        ->isSubscribed($list_id, $user->mail)) {
        if (!$cm
          ->subscribe($list_id, $user->mail, $user->name)) {
          form_set_error('', t('You were not subscribed to the list. Please try again later.'));
          $form_state['redirect'] = FALSE;
          return FALSE;
        }

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

      // Maybe this is an unsubscribe.
      if ($cm
        ->isSubscribed($list_id, $user->mail)) {
        if (!$cm
          ->unsubscribe($list_id, $user->mail)) {
          form_set_error('', t('You were not unsubscribed from the list(s). Please try again later.'));
          $form_state['redirect'] = FALSE;
          return FALSE;
        }

        // Check if the user should be sent to an unsubscribe page.
        if (isset($lists_info[$list_id]['details']['UnsubscribePage']) && !empty($lists_info[$list_id]['details']['UnsubscribePage'])) {
          drupal_goto($lists_info[$list_id]['details']['UnsubscribePage']);
        }
        else {
          drupal_set_message(t('You are now removed from the "@list" list.', [
            '@list' => $lists_info[$list_id]['name'],
          ]), 'status');
        }
      }
    }
  }
}

/**
 * Implements hook_form_FORM_ID_alter().
 */
function campaignmonitor_user_form_campaignmonitor_admin_settings_list_edit_alter(&$form, &$form_state, $form_id) {

  // Find form key to index the form array and load defaults.
  $form_key = 'campaignmonitor_list_' . $form['listId']['#value'];
  $defaults = variable_get($form_key, []);

  // Add option to enable this form on the user page.
  $form[$form_key]['display']['user'] = [
    '#type' => 'checkbox',
    '#title' => t('Display list on user page'),
    '#description' => t('Enable this list on the user page and allow subscription.'),
    '#default_value' => isset($defaults['display']['user']) ? $defaults['display']['user'] : 0,
  ];
}

/**
 * Implements hook_form_FORM_ID_alter().
 *
 * Adds the option to synchronize subscriptions with user updates to the general
 * settings form.
 */
function campaignmonitor_form_campaignmonitor_admin_settings_general_alter(&$form, &$form_state, $form_id) {
  $defaults = variable_get('campaignmonitor_general', []);
  $form['campaignmonitor_general']['synchronize'] = [
    '#type' => 'checkbox',
    '#title' => t('Synchronize e-mail address when updating user account.'),
    '#default_value' => isset($defaults['synchronize']) ? $defaults['synchronize'] : 0,
    '#description' => t('If checked, user e-mail adresses will be synchronized when users update their account.'),
  ];
}

/**
 * Implements hook_user_update().
 *
 * Makes sure that user e-mail addresses are synchronized with Campaign Monitor
 * when user accounts are updated, if this option has been enabledin the
 * administration interface.
 */
function campaignmonitor_user_update(&$edit, $account, $category) {

  // In $edit['mail'] we have the entered e-mail address, and in
  // $account->original->mail the original one before editing the account. If
  // they are equal, we do nothing.
  if (isset($edit['mail']) && $edit['mail'] != $account->original->mail && $category == 'account') {

    // Get Campaign Monitor settings and check if the e-mail address should be
    // synchronized.
    $settings = variable_get('campaignmonitor_general', []);
    if (isset($settings['synchronize']) && $settings['synchronize']) {
      $cm = CampaignMonitor::getConnector();
      $lists_info = $cm
        ->getLists();
      foreach ($lists_info as $list_id => $list) {

        // Check if the list is selected to be shown.
        $list_options = variable_get('campaignmonitor_list_' . $list_id, []);
        if (campaignmonitor_is_list_enabled($list_id) && isset($list_options['display']['user']) && $list_options['display']['user']) {

          // Check if the user is subscribed to the current list, but not yet
          // subscribed with the new e-mail.
          if ($cm
            ->isSubscribed($list_id, $account->original->mail) && !$cm
            ->isSubscribed($list_id, $edit['mail'])) {
            if ($cm
              ->updateSubscriberEmail($list_id, $account->original->mail, $edit['mail'])) {
              drupal_set_message(t('Your e-mail adress has been updated for the "@list" list.', [
                '@list' => $list['name'],
              ]), 'status');
            }
            else {
              drupal_set_message(t('Your e-mail adress has not been updated for the "@list" list.', [
                '@list' => $list['name'],
              ]), 'error');
            }
          }
        }
      }
    }
  }
}