Newer
Older
<?php
Lev Tsypin
committed
* @file
* Mailchimp module.
Lev Tsypin
committed
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Markup;
Gabriel Carleton-Barnes
committed
use Drupal\Core\Url;
use GuzzleHttp\Exception\ClientException;
Dan Ruscoe
committed
use Mailchimp\MailchimpLists;
define('MAILCHIMP_QUEUE_CRON', 'mailchimp');
define('MAILCHIMP_STATUS_SENT', 'sent');
define('MAILCHIMP_STATUS_SAVE', 'save');
define('MAILCHIMP_STATUS_PAUSED', 'paused');
define('MAILCHIMP_STATUS_SCHEDULE', 'schedule');
define('MAILCHIMP_STATUS_SENDING', 'sending');
/**
* Access callback for mailchimp submodule menu items.
*
* @return bool
* TRUE if the mailchimp api is available and accessible by the user.
*/
function mailchimp_apikey_ready_access($permission) {
if (mailchimp_get_api_object() && \Drupal::currentUser()->hasPermission($permission)) {
return TRUE;
}
return FALSE;
}
* Instantiates a Mailchimp library object.
* @return \Mailchimp\Mailchimp
* Drupal Mailchimp library object.
Andy Price
committed
function mailchimp_get_api_object($classname = 'MailchimpApiUser') {
$object = \Drupal::service('mailchimp.client_factory')->getByClassNameOrNull($classname);
if (!$object) {
\Drupal::messenger()->addError('Failed to load Mailchimp PHP library. Please refer to the installation requirements.');
return NULL;
}
$config = \Drupal::config('mailchimp.settings');
if (!$config->get('test_mode') && !$object->hasApiAccess()) {
$mc_oauth_url = Url::fromRoute('mailchimp.admin.oauth');
\Drupal::messenger()->addError(t('Unable to connect to Mailchimp API. Visit @oauth_settings_page to authenticate or uncheck "Use OAuth Authentication" and add an api_key below (deprecated).', ['@oauth_settings_page' => Link::fromTextAndUrl(t('OAuth Settings page'), $mc_oauth_url)->toString()]));
return NULL;
}
return $object;
Samuel Mortenson
committed
/**
* Gets the user agent string for this installation of Mailchimp.
*
* @return string
* The user agent string.
*/
function _mailchimp_get_user_agent() {
$version = '8.x-1.x';
if (\Drupal::moduleHandler()->moduleExists('system')) {
Primoz Hmeljak
committed
/** @var \Drupal\Core\Extension\ModuleExtensionList $extension_list */
$extension_list = \Drupal::service('extension.list.module');
$info = $extension_list->getExtensionInfo('mailchimp');
Samuel Mortenson
committed
if (!empty($info['version'])) {
$version = $info['version'];
}
}
$user_agent = "DrupalMailchimp/$version " . default_user_agent();
Samuel Mortenson
committed
return $user_agent;
}
Gabriel Carleton-Barnes
committed
/**
Gabriel Carleton-Barnes
committed
*
* @param string $list_id
* The unique ID of the list provided by Mailchimp.
Gabriel Carleton-Barnes
committed
*
* @return array
Gabriel Carleton-Barnes
committed
*/
function mailchimp_get_list($list_id) {
Samuel Mortenson
committed
$lists = mailchimp_get_lists([$list_id]);
Gabriel Carleton-Barnes
committed
return reset($lists);
}
* Returns all Mailchimp lists for a given key. Lists are stored in the cache.
*
* @param array $list_ids
* An array of list IDs to filter the results by.
* @param bool $reset
* Force a cache reset.
*
* @return array
Samuel Mortenson
committed
function mailchimp_get_lists(array $list_ids = [], $reset = FALSE) {
$lists = [];
$cache = \Drupal::cache('mailchimp');
$cached_data = $reset ? NULL : $cache->get('lists');
if ($cached_data) {
$lists = $cached_data->data;
try {
/** @var \Mailchimp\MailchimpLists $mcapi */
$mcapi = mailchimp_get_api_object('MailchimpLists');
Samuel Mortenson
committed
if ($mcapi != NULL) {
$result = $mcapi->getLists(['count' => 500]);
if ($result->total_items > 0) {
foreach ($result->lists as $list) {
Samuel Mortenson
committed
$int_category_data = $mcapi->getInterestCategories($list->id, ['count' => 500]);
if ($int_category_data->total_items > 0) {
Samuel Mortenson
committed
$list->intgroups = [];
foreach ($int_category_data->categories as $interest_category) {
Samuel Mortenson
committed
$interest_data = $mcapi->getInterests($list->id, $interest_category->id, ['count' => 500]);
if ($interest_data->total_items > 0) {
$interest_category->interests = $interest_data->interests;
}
$list->intgroups[] = $interest_category;
}
Greg Boggs
committed
}
$lists[$list->id] = $list;
Samuel Mortenson
committed
$mergefields = $mcapi->getMergeFields($list->id, ['count' => 500]);
if ($mergefields->total_items > 0) {
$lists[$list->id]->mergevars = $mergefields->merge_fields;
}
Greg Boggs
committed
}
Greg Boggs
committed
uasort($lists, '_mailchimp_list_cmp');
Greg Boggs
committed
$cache->set('lists', $lists);
}
Rebecca Jacobsen
committed
catch (\Exception $e) {
Samuel Mortenson
committed
\Drupal::logger('mailchimp')->error('An error occurred requesting list information from Mailchimp. "{message}"', [
'message' => $e->getMessage(),
]);
if (!empty($list_ids)) {
Samuel Mortenson
committed
$filtered_lists = [];
foreach ($list_ids as $id) {
if (array_key_exists($id, $lists)) {
$filtered_lists[$id] = $lists[$id];
}
}
return $filtered_lists;
}
else {
return $lists;
}
}
/**
* Helper function used by uasort() to sort lists alphabetically by name.
*
Samuel Mortenson
committed
* @param object $a
* An object representing the first list.
* @param object $b
* An object representing the second list.
*
* @return int
* One of the values -1, 0, 1
*/
function _mailchimp_list_cmp($a, $b) {
if ($a->name == $b->name) {
return ($a->name < $b->name) ? -1 : 1;
Gabriel Carleton-Barnes
committed
/**
* Wrapper around MailchimpLists->getMergeFields().
* Array of Mailchimp list IDs.
* @param bool $reset
* Set to TRUE if mergevars should not be loaded from cache.
Gabriel Carleton-Barnes
committed
* Struct describing mergevars for the specified lists.
*/
Samuel Mortenson
committed
function mailchimp_get_mergevars(array $list_ids, $reset = FALSE) {
$mergevars = [];
$cache = \Drupal::cache('mailchimp');
Gabriel Carleton-Barnes
committed
if (!$reset) {
foreach ($list_ids as $key => $list_id) {
$cached_data = $cache->get($list_id . '-mergevars');
// Get cached data and unset from our remaining lists to query.
if ($cached_data) {
$mergevars[$list_id] = $cached_data->data;
Gabriel Carleton-Barnes
committed
}
}
}
// Get the uncached merge vars from Mailchimp.
Gabriel Carleton-Barnes
committed
if (count($list_ids)) {
/** @var \Mailchimp\MailchimpLists $mc_lists */
$mc_lists = mailchimp_get_api_object('MailchimpLists');
$list_id = NULL;
if (!$mc_lists) {
throw new Exception('Cannot get merge vars without Mailchimp API. Check API key has been entered.');
}
foreach ($list_ids as $list_id) {
// Add default EMAIL merge var for all lists.
Samuel Mortenson
committed
$mergevars[$list_id] = [
(object) [
'tag' => 'EMAIL',
Peter Borsa
committed
'name' => t('Email Address'),
'type' => 'email',
'required' => TRUE,
'default_value' => '',
'public' => TRUE,
'display_order' => 1,
Samuel Mortenson
committed
'options' => (object) [
Samuel Mortenson
committed
],
],
];
Samuel Mortenson
committed
$result = $mc_lists->getMergeFields($list_id, ['count' => 500]);
if ($result->total_items > 0) {
$mergevars[$list_id] = array_merge($mergevars[$list_id], $result->merge_fields);
Gabriel Carleton-Barnes
committed
}
Balázs Sztreha
committed
$cache->set($list_id . '-mergevars', $mergevars[$list_id]);
Gabriel Carleton-Barnes
committed
}
Rebecca Jacobsen
committed
catch (\Exception $e) {
Samuel Mortenson
committed
\Drupal::logger('mailchimp')->error('An error occurred requesting mergevars for list {list}. "{message}"', [
'list' => $list_id,
Samuel Mortenson
committed
'message' => $e->getMessage(),
]);
Gabriel Carleton-Barnes
committed
}
}
return $mergevars;
}
* Get the Mailchimp member info for a given email address and list.
* Results are cached in the cache_mailchimp bin which is cleared by the
* Mailchimp web hooks system when needed.
* The Mailchimp list ID to get member info for.
* The Mailchimp user email address to load member info for.
* @param bool $reset
* Set to TRUE if member info should not be loaded from cache.
* @return object
* Member info object, empty if there is no valid info.
*/
function mailchimp_get_memberinfo($list_id, $email, $reset = FALSE) {
$cache = \Drupal::cache('mailchimp');
if (!$reset) {
$cached_data = $cache->get($list_id . '-' . $email);
if ($cached_data) {
return $cached_data->data;
}
// Query lists from the MCAPI and store in cache:
$memberinfo = new stdClass();
/** @var \Mailchimp\MailchimpLists $mc_lists */
$mc_lists = mailchimp_get_api_object('MailchimpLists');
throw new Exception('Cannot get member info without Mailchimp API. Check API key has been entered.');
}
$result = $mc_lists->getMemberInfo($list_id, $email);
if (!empty($result->id)) {
$memberinfo = $result;
$cache->set($list_id . '-' . $email, $memberinfo);
Rebecca Jacobsen
committed
catch (\Exception $e) {
// A 404 exception code means mailchimp does not have subscription
// information for given email address. This is not an error and we can
// cache this information.
if ($e->getCode() == 404) {
$cache->set($list_id . '-' . $email, $memberinfo);
}
else {
Samuel Mortenson
committed
\Drupal::logger('mailchimp')->error('An error occurred requesting memberinfo for {email} in list {list}. "{message}"', [
'email' => $email,
'list' => $list_id,
'message' => $e->getMessage(),
Samuel Mortenson
committed
]);
}
return $memberinfo;
}
/**
* Get the marketing permissions for a subscribed member.
*
* Simple wrapper around mailchimp_get_memberinfo().
*
* @param string $list_id
* Unique string identifier for the list on your MailChimp account.
* @param string $email
* Email address to check for on the identified MailChimp List.
* @param bool $reset
* Set to TRUE to ignore the cache. (Used heavily in testing functions.)
*
* @return array
* An array of marketing permissions, or an empty array if not subscribed
*/
function mailchimp_get_marketing_permissions($list_id, $email, $reset = FALSE) {
$memberinfo = mailchimp_get_memberinfo($list_id, $email, $reset);
if (isset($memberinfo->status)
Daniel Korte
committed
&& $memberinfo->status == MailchimpLists::MEMBER_STATUS_SUBSCRIBED
&& isset($memberinfo->marketing_permissions)) {
return $memberinfo->marketing_permissions;
}
return [];
}
Gabriel Carleton-Barnes
committed
* Check if the given email is subscribed to the given list.
Lev Tsypin
committed
*
Gabriel Carleton-Barnes
committed
* Simple wrapper around mailchimp_get_memberinfo().
*
* Unique string identifier for the list on your Mailchimp account.
Samuel Mortenson
committed
* Email address to check for on the identified Mailchimp List.
* Set to TRUE to ignore the cache. (Used heavily in testing functions.)
Lev Tsypin
committed
* @return bool
Gabriel Carleton-Barnes
committed
function mailchimp_is_subscribed($list_id, $email, $reset = FALSE) {
$subscribed = FALSE;
Gabriel Carleton-Barnes
committed
$memberinfo = mailchimp_get_memberinfo($list_id, $email, $reset);
Daniel Korte
committed
if (isset($memberinfo->status) && $memberinfo->status == MailchimpLists::MEMBER_STATUS_SUBSCRIBED) {
$subscribed = TRUE;
}
return $subscribed;
* Subscribe a user to a Mailchimp list in real time or by adding to the queue.
Lev Tsypin
committed
*
* @see Mailchimp_Lists::subscribe()
Abhishek Gupta
committed
function mailchimp_subscribe($list_id, $email, $merge_vars = NULL, $interests = [], $double_optin = FALSE, $format = 'html', $language = NULL, $gdpr_consent = FALSE, $tags = NULL) {
$config = \Drupal::config('mailchimp.settings');
Jakob Gehring
committed
if (empty($language)) {
$language = \Drupal::languageManager()->getCurrentLanguage()->getId();
}
if ($config->get('cron')) {
Samuel Mortenson
committed
$args = [
Lev Tsypin
committed
'list_id' => $list_id,
'email' => $email,
'merge_vars' => $merge_vars,
Lev Tsypin
committed
'double_optin' => $double_optin,
Jakob Gehring
committed
'language' => $language,
'gdpr_consent' => $gdpr_consent,
'tags' => $tags,
Samuel Mortenson
committed
];
Lev Tsypin
committed
return mailchimp_addto_queue('mailchimp_subscribe_process', $args);
}
return mailchimp_subscribe_process($list_id, $email, $merge_vars, $interests, $double_optin, $format, $language, $gdpr_consent, $tags);
Lev Tsypin
committed
}
/**
* Wrapper around Mailchimp_Lists::subscribe().
*
* @see Mailchimp_Lists::subscribe()
*/
function mailchimp_subscribe_process($list_id, $email, $merge_vars = NULL, $interests = [], $double_optin = FALSE, $format = 'html', $language = NULL, $gdpr_consent = FALSE, $tags = NULL) {
$config = \Drupal::config('mailchimp.settings');
Lev Tsypin
committed
$result = FALSE;
Lev Tsypin
committed
try {
/** @var \Mailchimp\MailchimpLists $mc_lists */
$mc_lists = mailchimp_get_api_object('MailchimpLists');
if (!$mc_lists) {
throw new Exception('Cannot subscribe to list without Mailchimp API. Check API key has been entered.');
Samuel Mortenson
committed
$parameters = [
Dan Ruscoe
committed
// If double opt-in is required, set member status to 'pending'.
Samuel Mortenson
committed
'status' => ($double_optin) ? MailchimpLists::MEMBER_STATUS_PENDING : MailchimpLists::MEMBER_STATUS_SUBSCRIBED,
Samuel Mortenson
committed
];
Jakob Gehring
committed
if (!empty($language)) {
$parameters['language'] = $language;
}
// Set interests.
if (!empty($interests)) {
Samuel Mortenson
committed
$selected_interests = [];
foreach ($interests as $interest_group) {
git
committed
// This could happen in case the selected interest group
// is set to display radio inputs. So we either do an
// explicit check here, or simply transform the single string
// value to an array in order to pass the condition check below.
if (!is_array($interest_group)) {
$interest_group = [$interest_group => $interest_group];
}
foreach ($interest_group as $interest_id => $interest_status) {
$selected_interests[$interest_id] = ($interest_status !== 0);
}
}
if (!empty($selected_interests)) {
$parameters['interests'] = (object) $selected_interests;
}
}
// Set merge fields.
if (!empty($merge_vars)) {
$parameters['merge_fields'] = (object) $merge_vars;
}
// Has GDPR consent been given?
if ($gdpr_consent) {
// If the member is already subscribed get the marketing permission id(s)
// for the list and enable them.
$marketing_permissions = mailchimp_get_marketing_permissions($list_id, $email);
$was_subscribed = FALSE;
if ($marketing_permissions) {
foreach ($marketing_permissions as $marketing_permission) {
$parameters['marketing_permissions'][] = [
'marketing_permission_id' => $marketing_permission->marketing_permission_id,
'enabled' => TRUE,
];
}
$was_subscribed = TRUE;
}
}
else {
// We need to make sure this is set.
$was_subscribed = FALSE;
}
Samuel Mortenson
committed
// Add member to list.
$result = $mc_lists->addOrUpdateMember($list_id, $email, $parameters);
Samuel Mortenson
committed
\Drupal::moduleHandler()->invokeAll('mailchimp_subscribe_success', [
$list_id,
$email,
$merge_vars,
]);
// Clear user cache, just in case there's some cruft leftover:
Lev Tsypin
committed
mailchimp_cache_clear_member($list_id, $email);
Samuel Mortenson
committed
\Drupal::logger('mailchimp')->notice('{email} was subscribed to list {list}.', [
Vladimir Mitrovic
committed
'email' => $email,
Samuel Mortenson
committed
]);
// For newly subscribed members set GDPR consent if it's been given.
if (!$was_subscribed && $gdpr_consent && !empty($result->marketing_permissions)) {
Samuel Mortenson
committed
// If the member is already subscribed get the marketing permission
// id(s) for the list and enable them.
foreach ($result->marketing_permissions as $marketing_permission) {
$parameters['marketing_permissions'][] = [
'marketing_permission_id' => $marketing_permission->marketing_permission_id,
'enabled' => TRUE,
];
}
Samuel Mortenson
committed
// Update the member.
$result = $mc_lists->addOrUpdateMember($list_id, $email, $parameters);
if (!isset($result->id)) {
\Drupal::logger('mailchimp')
Samuel Mortenson
committed
->warning('A problem occurred setting marketing permissions for {email} on list {list}.', [
'email' => $email,
'list' => $list_id,
Chris Burgess
committed
]);
}
}
Chris Burgess
committed
if ($double_optin) {
$msg = $config->get('optin_check_email_msg');
if ($msg) {
\Drupal::messenger()->addStatus($msg, FALSE);
}
Chris Burgess
committed
}
// Add or update member tags.
$tags = array_map('trim', $tags);
try {
$mc_lists->addTagsMember($list_id, $tags, $email);
}
catch (ClientException $e) {
\Drupal::logger('mailchimp')->error('An error occurred while adding tags for this email({email}) to Mailchimp: {message}', [
'message' => $e->getMessage(),
'email' => $email,
]);
}
}
Lev Tsypin
committed
}
else {
if (!$config->get('test_mode')) {
Samuel Mortenson
committed
\Drupal::logger('mailchimp')->warning('A problem occurred subscribing {email} to list {list}.', [
'email' => $email,
'list' => $list_id,
Samuel Mortenson
committed
]);
Gabriel Carleton-Barnes
committed
}
Rebecca Jacobsen
committed
catch (\Exception $e) {
Dan Ruscoe
committed
if ($e->getCode() == '400' && strpos($e->getMessage(), 'Member In Compliance State') !== FALSE && !$double_optin) {
Samuel Mortenson
committed
\Drupal::logger('mailchimp')->error('Detected "Member In Compliance State" subscribing {email} to list {list}. Trying again using double-opt in.', [
'email' => $email,
'list' => $list_id,
Samuel Mortenson
committed
]);
return mailchimp_subscribe_process($list_id, $email, $merge_vars, $interests, TRUE, $format, $language, $gdpr_consent, $tags);
Dan Ruscoe
committed
}
Samuel Mortenson
committed
\Drupal::logger('mailchimp')->error('An error occurred subscribing {email} to list {list}. "{message}"', [
'email' => $email,
'list' => $list_id,
'message' => $e->getMessage(),
Samuel Mortenson
committed
]);
}
Gabriel Carleton-Barnes
committed
Lev Tsypin
committed
return $result;
}
/**
* Adds a Mailchimp subscription task to the queue.
Lev Tsypin
committed
*
Lev Tsypin
committed
* The name of the function the queue runner should call.
Lev Tsypin
committed
* The list of args to pass to the function.
*
* @return mixed
* Unique ID if item is successfully added to the queue, FALSE otherwise.
*/
Samuel Mortenson
committed
function mailchimp_addto_queue($function, array $args) {
$queue = \Drupal::queue(MAILCHIMP_QUEUE_CRON);
Lev Tsypin
committed
$queue->createQueue();
Samuel Mortenson
committed
return $queue->createItem([
Lev Tsypin
committed
'function' => $function,
'args' => $args,
Samuel Mortenson
committed
]);
Lev Tsypin
committed
}
Lev Tsypin
committed
/**
* Update a members list subscription in real time or by adding to the queue.
*
* @see Mailchimp_Lists::updateMember()
*/
derekw
committed
function mailchimp_update_member($list_id, $email, $merge_vars, $interests = [], $format = 'html', $double_optin = FALSE, $gdpr_consent = FALSE, $tags = NULL) {
$config = \Drupal::config('mailchimp.settings');
if ($config->get('cron')) {
Samuel Mortenson
committed
$args = [
Lev Tsypin
committed
'list_id' => $list_id,
'email' => $email,
'merge_vars' => $merge_vars,
'tags' => $tags,
Lev Tsypin
committed
'format' => $format,
Dan Ruscoe
committed
'double_optin' => $double_optin,
'gdpr_consent' => $gdpr_consent,
Samuel Mortenson
committed
];
Lev Tsypin
committed
return mailchimp_addto_queue('mailchimp_update_member_process', $args);
Lev Tsypin
committed
}
return mailchimp_update_member_process($list_id, $email, $merge_vars, $interests, $format, $double_optin, $gdpr_consent, $tags);
Lev Tsypin
committed
}
/**
* Wrapper around Mailchimp_Lists::updateMember().
*
Lev Tsypin
committed
* @see Mailchimp_Lists::updateMember()
*/
derekw
committed
function mailchimp_update_member_process($list_id, $email, $merge_vars, $interests, $format, $double_optin = FALSE, $gdpr_consent = FALSE, $tags = NULL) {
$config = \Drupal::config('mailchimp.settings');
Lev Tsypin
committed
$result = FALSE;
Lev Tsypin
committed
try {
/** @var \Mailchimp\MailchimpLists $mc_lists */
$mcapi = mailchimp_get_api_object('MailchimpLists');
Samuel Mortenson
committed
$parameters = [
Dan Ruscoe
committed
'status' => ($double_optin) ? MailchimpLists::MEMBER_STATUS_PENDING : MailchimpLists::MEMBER_STATUS_SUBSCRIBED,
Samuel Mortenson
committed
];
// Set interests.
if (!empty($interests)) {
Samuel Mortenson
committed
$selected_interests = [];
foreach ($interests as $interest_group) {
foreach ($interest_group as $interest_id => $interest_status) {
$selected_interests[$interest_id] = ($interest_status !== 0);
}
}
if (!empty($selected_interests)) {
$parameters['interests'] = (object) $selected_interests;
}
}
// Set merge fields.
if (!empty($merge_vars)) {
$parameters['merge_fields'] = (object) $merge_vars;
}
// Has GDPR consent been given?
if ($gdpr_consent) {
// If the member is already subscribed get the marketing permission id(s)
// for the list and enable them.
$marketing_permissions = mailchimp_get_marketing_permissions($list_id, $email);
if ($marketing_permissions) {
foreach ($marketing_permissions as $marketing_permission) {
$parameters['marketing_permissions'][] = [
'marketing_permission_id' => $marketing_permission->marketing_permission_id,
'enabled' => TRUE,
];
}
}
}
Samuel Mortenson
committed
// Update member.
$result = $mcapi->updateMember($list_id, $email, $parameters);
if (isset($result->id)) {
Samuel Mortenson
committed
\Drupal::logger('mailchimp')->notice('{email} was updated in list {list_id}.', [
'email' => $email,
'list' => $list_id,
Samuel Mortenson
committed
]);
Lev Tsypin
committed
// Clear user cache:
mailchimp_cache_clear_member($list_id, $email);
Lev Tsypin
committed
else {
Samuel Mortenson
committed
\Drupal::logger('mailchimp')->warning('A problem occurred updating {email} on list {list}.', [
'email' => $email,
'list' => $list_id,
Samuel Mortenson
committed
]);
Lev Tsypin
committed
}
Rebecca Jacobsen
committed
catch (\Exception $e) {
Dan Ruscoe
committed
if ($e->getCode() == '400' && strpos($e->getMessage(), 'Member In Compliance State') !== FALSE && !$double_optin) {
Samuel Mortenson
committed
\Drupal::logger('mailchimp')->error('Detected "Member In Compliance State" subscribing {email} to list {list}. Trying again using double-opt in.', [
'email' => $email,
'list' => $list_id,
Samuel Mortenson
committed
]);
Dan Ruscoe
committed
derekw
committed
return mailchimp_update_member_process($list_id, $email, $merge_vars, $interests, $format, TRUE, $gdpr_consent, $tags);
Dan Ruscoe
committed
}
Samuel Mortenson
committed
\Drupal::logger('mailchimp')->error('An error occurred updating {email} on list {list}. "{message}"', [
'email' => $email,
'list' => $list_id,
'message' => $e->getMessage(),
Samuel Mortenson
committed
]);
Lev Tsypin
committed
}
Dan Ruscoe
committed
if ($double_optin) {
$msg = $config->get('optin_check_email_msg');
if ($msg) {
\Drupal::messenger()->addStatus($msg, FALSE);
}
Dan Ruscoe
committed
}
derekw
committed
// Add or update member tags
if ($tags) {
$tags = explode(',', (string) $tags);
$tags = array_map('trim', $tags);
try {
$mcapi->addTagsMember($list_id, $tags, $email);
}
catch (ClientException $e) {
\Drupal::logger('mailchimp')->error('An error occurred while adding tags for this email({email}) to Mailchimp: {message}', [
'message' => $e->getMessage(),
'email' => $email,
]);
}
}
Lev Tsypin
committed
return $result;
/**
* Retrieve all members of a given list with a given status.
*
* Note that this function can cause locking an is somewhat slow. It is not
* recommended unless you know what you are doing! See the MCAPI documentation.
*/
Daniel Korte
committed
function mailchimp_get_members($list_id, $status = MailchimpLists::MEMBER_STATUS_SUBSCRIBED, $options = []) {
$results = FALSE;
$lock = \Drupal::lock();
if ($lock->acquire('mailchimp_get_members', 60)) {
/** @var \Mailchimp\MailchimpLists $mcapi */
$mcapi = mailchimp_get_api_object('MailchimpLists');
$options['status'] = $status;
$options['count'] = 500;
$results = $mcapi->getMembers($list_id, $options);
Rebecca Jacobsen
committed
catch (\Exception $e) {
Samuel Mortenson
committed
\Drupal::logger('mailchimp')->error('An error occurred pulling member info for a list. "{message}"', [
'message' => $e->getMessage(),
]);
$lock->release('mailchimp_get_members');
return $results;
}
* Batch updates a number of Mailchimp list members.
* @see Mailchimp_Lists::batchSubscribe()
function mailchimp_batch_update_members($list_id, $batch) {
/** @var \Mailchimp\MailchimpLists $mc_lists */
$mc_lists = mailchimp_get_api_object('MailchimpLists');
if (!$mc_lists) {
throw new Exception('Cannot batch subscribe to list without Mailchimp API. Check API key has been entered.');
}
if (!empty($batch)) {
// Create a new batch update operation for each member.
foreach ($batch as $batch_data) {
// @todo Remove 'advanced' earlier? Needed at all?
unset($batch_data['merge_vars']['advanced']);
Samuel Mortenson
committed
$parameters = [
'email_type' => $batch_data['email_type'],
'merge_fields' => (object) $batch_data['merge_vars'],
Samuel Mortenson
committed
];
$mc_lists->addOrUpdateMember($list_id, $batch_data['email'], $parameters, TRUE);
}
// Process batch operations.
return $mc_lists->processBatchOperations();
}
Rebecca Jacobsen
committed
catch (\Exception $e) {
Samuel Mortenson
committed
\Drupal::logger('mailchimp')->error('An error occurred performing batch subscribe/update. "{message}"', [
'message' => $e->getMessage(),
]);
return $results;
}
* Unsubscribes a member from a Mailchimp list.
Lev Tsypin
committed
*
Rebecca Jacobsen
committed
function mailchimp_unsubscribe($list_id, $email) {
$config = \Drupal::config('mailchimp.settings');
$result = FALSE;
if (mailchimp_is_subscribed($list_id, $email)) {
if ($config->get('cron')) {
$result = mailchimp_addto_queue(
'mailchimp_unsubscribe_process',
Samuel Mortenson
committed
[
'list_id' => $list_id,
'email' => $email,
Samuel Mortenson
committed
]
Rebecca Jacobsen
committed
$result = mailchimp_unsubscribe_process($list_id, $email);
}
}
return $result;
}
/**
* Unsubscribes a member from a Mailchimp list.
*
* @see Mailchimp_Lists::unsubscribe()
*/
Rebecca Jacobsen
committed
function mailchimp_unsubscribe_process($list_id, $email) {
/** @var \Mailchimp\MailchimpLists $mc_lists */
$mc_lists = mailchimp_get_api_object('MailchimpLists');
if (!$mc_lists) {
throw new Exception('Cannot unsubscribe from list without Mailchimp API. Check API key has been entered.');
Daniel Korte
committed
$mc_lists->updateMember($list_id, $email, ['status' => MailchimpLists::MEMBER_STATUS_UNSUBSCRIBED]);
\Drupal::moduleHandler()->invokeAll('mailchimp_unsubscribe_success', [
$list_id,
$email,
]);
// Clear user cache:
mailchimp_cache_clear_member($list_id, $email);
return TRUE;
Rebecca Jacobsen
committed
catch (\Exception $e) {
Samuel Mortenson
committed
\Drupal::logger('mailchimp')->error('An error occurred unsubscribing {email} from list {list}. "{message}"', [
'email' => $email,
'list' => $list_id,
'message' => $e->getMessage(),
Samuel Mortenson
committed
]);
return FALSE;
Samuel Mortenson
committed
* Wrapper function to return data for a given campaign.
* Data is stored in the Mailchimp cache.
* @param string $campaign_id
* The ID of the campaign to get data for.
* @param bool $reset
* Set to TRUE if campaign data should not be loaded from cache.
*
* @return mixed
* Array of campaign data or FALSE if not found.
*/
function mailchimp_get_campaign_data($campaign_id, $reset = FALSE) {
$cache = \Drupal::cache('mailchimp');
if (!$reset) {
$cached_data = $cache->get('campaign_' . $campaign_id);
if ($cached_data) {
return $cached_data->data;
}
/** @var \Mailchimp\MailchimpCampaigns $mcapi */
$mcapi = mailchimp_get_api_object('MailchimpCampaigns');
$response = $mcapi->getCampaign($campaign_id);
if (!empty($response->id)) {
$campaign_data = $response;
$cache->set('campaign_' . $campaign_id, $campaign_data);
Rebecca Jacobsen
committed
catch (\Exception $e) {
Samuel Mortenson
committed
\Drupal::logger('mailchimp')->error('An error occurred retrieving campaign data for {campaign}. "{message}"', [
'campaign' => $campaign_id,
'message' => $e->getMessage(),
Samuel Mortenson
committed
]);
return $campaign_data;
}
/**
* Returns all lists a given email address is currently subscribed to.
*
* @param string $email
* Email address to search.
*
* @return array
* Campaign structs containing id, web_id, name.
*/
function mailchimp_get_lists_for_email($email) {
try {
/** @var \Mailchimp\MailchimpLists $mcapi */
$mcapi = mailchimp_get_api_object('MailchimpLists');
$lists = $mcapi->getListsForEmail($email);
}
Rebecca Jacobsen
committed
catch (\Exception $e) {
Samuel Mortenson
committed
\Drupal::logger('mailchimp')->error('An error occurred retreiving lists data for {email}. "{message}"', [
'email' => $email,
'message' => $e->getMessage(),
Samuel Mortenson
committed
]);
Samuel Mortenson
committed
$lists = [];
}
return $lists;
}
Gabriel Carleton-Barnes
committed
/**
* Returns all webhooks for a given Mailchimp list ID.
Gabriel Carleton-Barnes
committed
*
Gabriel Carleton-Barnes
committed
*/
function mailchimp_webhook_get($list_id) {
try {
/** @var \Mailchimp\MailchimpLists $mc_lists */
$mc_lists = mailchimp_get_api_object('MailchimpLists');
$result = $mc_lists->getWebhooks($list_id);
return ($result->total_items > 0) ? $result->webhooks : FALSE;
}
Rebecca Jacobsen
committed
catch (\Exception $e) {
Samuel Mortenson
committed
\Drupal::logger('mailchimp')->error('An error occurred reading webhooks for list {list}. "{message}"', [
'list' => $list_id,
'message' => $e->getMessage(),
Samuel Mortenson
committed
]);
Gabriel Carleton-Barnes
committed
* Adds a webhook to a Mailchimp list.
Gabriel Carleton-Barnes
committed
*
* The Mailchimp list ID to add a webhook for.
Samuel Mortenson
committed
* @param array $events
* Associative array of events action to bool, indicating enabled status.
* @param array $sources
* Associative array of source name to bool, indicating source status.
*
* @return string
* The ID of the new webhook.
Samuel Mortenson
committed
*
* @see Mailchimp_Lists::addWebhook()
Samuel Mortenson
committed
function mailchimp_webhook_add($list_id, $url, array $events = [], array $sources = []) {
/** @var \Mailchimp\MailchimpLists $mc_lists */
$mc_lists = mailchimp_get_api_object('MailchimpLists');