You are here

mailchimp_lists.install in Mailchimp 7.2

Install, update and uninstall functions for the mailchimp_lists module.

File

modules/mailchimp_lists/mailchimp_lists.install
View source
<?php

/**
 * @file
 * Install, update and uninstall functions for the mailchimp_lists module.
 *
 */

// These are deprecated globals, but we need them here for update functions.
define('MAILCHIMP_LISTTYPE_REQUIRED', 'required');
define('MAILCHIMP_LISTTYPE_OPTIONAL', 'optional');
define('MAILCHIMP_LISTTYPE_FREEFORM', 'freeform');

/**
 * Implements hook_schema().
 */
function mailchimp_lists_schema() {
  $schema['mailchimp_lists'] = array(
    'fields' => array(
      'id' => array(
        'type' => 'serial',
        'not null' => TRUE,
        'description' => 'Primary Key: Unique mailchimp_list entity ID.',
      ),
      'name' => array(
        'description' => 'The machine-readable name of this mailchimp_list type.',
        'type' => 'varchar',
        'length' => 32,
        'not null' => TRUE,
      ),
      'mc_list_id' => array(
        'type' => 'varchar',
        'not null' => TRUE,
        'length' => 32,
        'description' => 'The MailChimp list id associated with this list.',
      ),
      'label' => array(
        'type' => 'varchar',
        'length' => 32,
        'description' => 'The {mailchimp_lists}.label of this mailchimp_list.',
        'not null' => TRUE,
        'default' => '',
      ),
      'description' => array(
        'type' => 'varchar',
        'length' => 255,
        'description' => 'The {mailchimp_lists}.description of this mailchimp_list.',
        'not null' => FALSE,
        'default' => '',
      ),
      'settings' => array(
        'type' => 'blob',
        'not null' => FALSE,
        'size' => 'big',
        'serialize' => TRUE,
        'description' => 'A serialized object that stores the settings for the specific list.',
      ),
      'status' => array(
        'type' => 'int',
        'not null' => TRUE,
        // Set the default to ENTITY_CUSTOM without using the constant as it is
        // not safe to use it at this point.
        'default' => 0x1,
        'size' => 'tiny',
        'description' => 'The exportable status of the entity.',
      ),
      'module' => array(
        'description' => 'The name of the providing module if the entity has been defined in code.',
        'type' => 'varchar',
        'length' => 255,
        'not null' => FALSE,
      ),
    ),
    'primary key' => array(
      'id',
    ),
    'unique key' => array(
      'name',
    ),
  );
  return $schema;
}

/**
 * Implements hook_install().
 */
function mailchimp_lists_install() {

  // Convert old lists if they exist:
  $old_lists = variable_get('mailchimp_lists', array());
  if (!empty($old_lists)) {
    $cron = variable_get('mailchimp_cron', FALSE);
    $register = variable_get('mailchimp_user_register', FALSE);
    $user = variable_get('mailchimp_user_edit', FALSE);
    $intgroups = variable_get('mailchimp_interest_groups_user_forms', FALSE);
    foreach ($old_lists as $id => $old_list) {
      $list = new stdClass();
      $list->mc_list_id = $id;
      $list->label = substr($old_list->label, 0, 32);
      $list->name = substr($old_list->name, 0, 32);
      $list->description = $old_list->description;
      $list->list_type = $old_list->list_type == 'required' ? MAILCHIMP_LISTTYPE_REQUIRED : MAILCHIMP_LISTTYPE_OPTIONAL;
      $list->settings = array(
        'roles' => $old_list->roles,
        'mergefields' => isset($old_list->mergevars) ? $old_list->mergevars : NULL,
        'show_register_form' => $register,
        'show_account_form' => $user,
        'include_interest_groups' => $intgroups,
        'cron' => $cron,
        'webhooks' => FALSE,
      );
      $t = get_t();
      if ($ret = mailchimp_lists_save($list)) {
        drupal_set_message($t('List @name has been converted.', array(
          '@name' => $list->label,
        )));
      }
      else {
        drupal_set_message($t('There has been an error converting list @name.', array(
          '@name' => $list->label,
        )), 'error');
      }
    }
  }

  // Now delete old variables:
  variable_del('mailchimp_cron');
  variable_del('mailchimp_interest_groups_user_forms');
  variable_del('mailchimp_lists');
  variable_del('mailchimp_user_edit');
  variable_del('mailchimp_user_register');
}

/**
 * Implements hook_uninstall().
 */
function mailchimp_lists_uninstall() {
  module_load_include('module', 'mailchimp_lists');
  $queue = DrupalQueue::get(MAILCHIMP_QUEUE_CRON);
  $queue
    ->deleteQueue();
}

/**
 * Add name, status, and module fields to make lists exportable.
 */
function mailchimp_lists_update_7200() {

  // The update was previously broken. To fix the broken state, we need to
  // remove the left-over field first.
  if (db_field_exists('mailchimp_lists', 'name')) {
    db_drop_field('mailchimp_lists', 'name');
  }

  // Add the machine name field.
  db_add_field('mailchimp_lists', 'name', array(
    'description' => 'The machine-readable name of this mailchimp_list.',
    'type' => 'varchar',
    'length' => 32,
    'not null' => FALSE,
  ));

  // Add the exportable status field.
  if (!db_field_exists('mailchimp_lists', 'status')) {
    db_add_field('mailchimp_lists', 'status', array(
      'type' => 'int',
      'not null' => TRUE,
      // Set the default to ENTITY_CUSTOM without using the constant as it is
      // not safe to use it at this point.
      'default' => 0x1,
      'size' => 'tiny',
      'description' => 'The exportable status of the entity.',
    ));
  }

  // Add the exportable module field.
  if (!db_field_exists('mailchimp_lists', 'module')) {
    db_add_field('mailchimp_lists', 'module', array(
      'description' => 'The name of the providing module if the entity has been defined in code.',
      'type' => 'varchar',
      'length' => 255,
      'not null' => FALSE,
    ));
  }

  // Generate a machine name for existing lists.
  $lists = db_select('mailchimp_lists', 'm')
    ->fields('m')
    ->execute()
    ->fetchAll();
  foreach ($lists as $list) {
    $list->name = strtolower(str_replace(' ', '_', $list->label));
    db_update('mailchimp_lists')
      ->fields(array(
      'name' => substr($list->name, 0, 32),
    ))
      ->condition('id', $list->id)
      ->execute();
  }

  // Now set the name field to be required.
  db_change_field('mailchimp_lists', 'name', 'name', array(
    'description' => 'The machine-readable name of this mailchimp_list.',
    'type' => 'varchar',
    'length' => 32,
    'not null' => TRUE,
  ));
}

/**
 * Add a unique key for the machine name field.
 */
function mailchimp_lists_update_7201() {
  db_add_unique_key('mailchimp_lists', 'name', array(
    'name',
  ));
}

/**
 * Convert block deltas from ID numbers to machine names.
 */
function mailchimp_lists_update_7202() {
  $num_updated = 0;
  $num_deleted = 0;
  $query = db_select('block', 'b')
    ->fields('b', array(
    'bid',
    'delta',
    'module',
    'theme',
  ))
    ->condition('module', 'mailchimp_lists', '=')
    ->execute();
  $results = $query
    ->fetchAll();
  foreach ($results as $result) {
    if (is_numeric($result->delta)) {
      $list_query = db_select('mailchimp_lists', 'm')
        ->fields('m', array(
        'name',
      ))
        ->condition('id', $result->delta)
        ->execute();
      $list_results = $list_query
        ->fetchAll();
      if ($list_results) {
        $list_machine_name = $list_results[0]->name;

        // Check to see if a machine name delta already exists:
        $check_query = db_select('block', 'b')
          ->fields('b', array(
          'bid',
          'delta',
        ))
          ->condition('delta', $list_machine_name, '=')
          ->condition('module', $result->module, '=')
          ->condition('theme', $result->theme, '=')
          ->execute();
        $check_results = $check_query
          ->fetchAll();
        if (count($check_results)) {

          // Delete the numeric fields:
          $num_deleted += db_delete('block')
            ->condition('bid', $result->bid, '=')
            ->execute();
        }
        else {
          $num_updated += db_update('block')
            ->fields(array(
            'delta' => $list_machine_name,
          ))
            ->condition('bid', $result->bid, '=')
            ->execute();
        }
      }
    }
  }
  if ($num_deleted > 0) {
    return t('Deleted !num duplicate block(s).', array(
      '!num' => $num_deleted,
    ));
  }
  elseif ($num_updated > 0) {
    return t('Updated !num block(s).', array(
      '!num' => $num_updated,
    ));
  }
  else {
    return TRUE;
  }
}

/**
 * Update list webhook endpoint URLs to be more secure.
 */
function mailchimp_lists_update_7203() {
  $efq = new EntityFieldQuery();
  $results = $efq
    ->entityCondition('entity_type', 'mailchimp_list')
    ->propertyCondition('list_type', array(
    MAILCHIMP_LISTTYPE_OPTIONAL,
    MAILCHIMP_LISTTYPE_REQUIRED,
  ), 'IN')
    ->execute();
  if (empty($results)) {
    return t('There are no lists to update.');
  }
  $lists = mailchimp_lists_load_multiple(array_keys($results['mailchimp_list']));
  $mcapi = mailchimp_get_api_object();

  // This is the old format of the webhook URL, used below.
  $old_url = $GLOBALS['base_url'] . '/mailchimp/webhook/' . md5($GLOBALS['base_url']);
  foreach ($lists as $list) {
    if (isset($list->settings['webhooks']) && $list->settings['webhooks']) {

      // Delete the old webhook.
      $ret = $mcapi
        ->listWebhookDel($list->mc_list_id, $old_url);
      if (!$ret) {
        return t('Failed to delete old web hook for @list', array(
          '@list' => $list->label,
        ));
      }

      // Now add the new one.
      $ret = $mcapi
        ->listWebhookAdd($list->mc_list_id, mailchimp_webhook_url(), array(
        'unsubscribe',
        'profile',
        'cleaned',
        'upemail',
      ));
      if (!$ret) {
        return t('Failed to create new web hook for @list', array(
          '@list' => $list->label,
        ));
      }
    }
  }
  return t('MailChimp list webhooks have been updated with the new, more secure endpoint URL.');
}

/**
 * Update list->settings with ['form_label'] index.
 */
function mailchimp_lists_update_7204() {
  $lists = db_select('mailchimp_lists', 'm')
    ->fields('m', array(
    'id',
    'label',
    'settings',
  ))
    ->execute()
    ->fetchAll();
  if (empty($lists)) {
    return t('There are no lists to update.');
  }
  $success = TRUE;
  foreach ($lists as $list) {
    $result = TRUE;
    $settings = unserialize($list->settings);
    if (!array_key_exists('form_label', $settings)) {
      $settings['form_label'] = $list->label;
      $settings = serialize($settings);
      $result = db_update('mailchimp_lists')
        ->fields(array(
        'settings' => $settings,
      ))
        ->condition('id', $list->id)
        ->execute();
    }
    $success = $result && $success;
  }
  $t = get_t();
  if ($success) {
    return $t('MailChimp lists have been given a default Form Label field value.');
  }
  else {
    throw new DrupalUpdateException('There was a problem updating your Mailchimp Lists configuration. Either roll back your database or go to the Mailchimp Lists configuration page and re-configure each list individually.');
  }
}

/**
 * Update list->settings with new values, remove list_type data and rebuild the registry.
 */
function mailchimp_lists_update_7205() {

  // Rebuild the registry to reflect the updated module structure.
  registry_rebuild();
  $lists = db_select('mailchimp_lists', 'm')
    ->fields('m', array(
    'id',
    'list_type',
    'settings',
  ))
    ->execute()
    ->fetchAll();
  if (empty($lists)) {
    return t('There are no lists to update.');
  }
  $success = TRUE;
  foreach ($lists as $list) {
    $settings = unserialize($list->settings);
    $result = TRUE;
    if (isset($list->list_type)) {
      switch ($list->list_type) {
        case MAILCHIMP_LISTTYPE_FREEFORM:
          $settings['required'] = FALSE;
          $settings['allow_anonymous'] = TRUE;
          $settings['roles'][DRUPAL_ANONYMOUS_RID] = TRUE;
          if (isset($settings['mergefields'])) {
            $settings['mergefields_display'] = array();
            foreach ($settings['mergefields'] as $id => $field) {
              $settings['mergefields_display'][$id] = 'TRUE';
            }
          }
          break;
        case MAILCHIMP_LISTTYPE_OPTIONAL:
          $settings['required'] = FALSE;
          $settings['allow_anonymous'] = FALSE;
          break;
        case MAILCHIMP_LISTTYPE_REQUIRED:
          $settings['required'] = TRUE;
          $settings['allow_anonymous'] = FALSE;
          break;
      }

      // This is where we would delete the list_type variable if we deemed it a
      // good idea. It is minimal cruft, however, and allows for back-revving
      // one's Mailchimp install more easily.
      $settings = serialize($settings);
      $result = db_update('mailchimp_lists')
        ->fields(array(
        'settings' => $settings,
      ))
        ->condition('id', $list->id)
        ->execute();
    }
    $success = $result && $success;
  }
  unset($lists);
  if ($success) {
    db_drop_field('mailchimp_lists', 'list_type');
    drupal_get_schema('mailchimp_lists', TRUE);
    $t = get_t();
    return $t('MailChimp lists have been updated with new settings.');
  }
  else {
    throw new DrupalUpdateException('There was a problem updating your Mailchimp Lists configuration. Either roll back your database or go to the Mailchimp Lists configuration page and re-configure each list individually.');
  }
}

/**
 * Drop the created and updated fields from the {mailchimp_lists} schema.
 */
function mailchimp_lists_update_7206() {
  db_drop_field('mailchimp_lists', 'created');
  db_drop_field('mailchimp_lists', 'updated');
  drupal_get_schema('mailchimp_lists', TRUE);
}

Functions

Namesort descending Description
mailchimp_lists_install Implements hook_install().
mailchimp_lists_schema Implements hook_schema().
mailchimp_lists_uninstall Implements hook_uninstall().
mailchimp_lists_update_7200 Add name, status, and module fields to make lists exportable.
mailchimp_lists_update_7201 Add a unique key for the machine name field.
mailchimp_lists_update_7202 Convert block deltas from ID numbers to machine names.
mailchimp_lists_update_7203 Update list webhook endpoint URLs to be more secure.
mailchimp_lists_update_7204 Update list->settings with ['form_label'] index.
mailchimp_lists_update_7205 Update list->settings with new values, remove list_type data and rebuild the registry.
mailchimp_lists_update_7206 Drop the created and updated fields from the {mailchimp_lists} schema.

Constants