/**
  * Process the feed, subscribe the user to the list.
  *
  * @param array $entry The entry object currently being processed.
  * @param array $form The form object currently being processed.
  * @param array $feed The feed object currently being processed.
  */
 public function export_feed($entry, $form, $feed)
 {
     $resubscribe = $feed['meta']['resubscribe'] ? true : false;
     $email = $this->get_field_value($form, $entry, $feed['meta']['listFields_email']);
     $name = '';
     if (!empty($feed['meta']['listFields_fullname'])) {
         $name = $this->get_field_value($form, $entry, $feed['meta']['listFields_fullname']);
     }
     $merge_vars = array();
     $field_maps = $this->get_field_map_fields($feed, 'listFields');
     foreach ($field_maps as $var_key => $field_id) {
         if (!in_array($var_key, array('email', 'fullname'))) {
             $values = $this->get_field_value($form, $entry, $field_id);
             if (!is_array($values)) {
                 $values = array($values);
             }
             foreach ($values as $value) {
                 $merge_vars[] = array('Key' => $var_key, 'Value' => $value);
             }
         }
     }
     $override_custom_fields = gf_apply_filters('gform_campaignmonitor_override_blank_custom_fields', $form['id'], false, $entry, $form, $feed);
     if (!$override_custom_fields) {
         $merge_vars = $this->remove_blank_custom_fields($merge_vars);
     }
     $subscriber = array('EmailAddress' => $email, 'Name' => $name, 'CustomFields' => $merge_vars, 'Resubscribe' => $resubscribe);
     $subscriber = gf_apply_filters('gform_campaignmonitor_override_subscriber', $form['id'], $subscriber, $entry, $form, $feed);
     $this->include_api();
     $api = new CS_REST_Subscribers($feed['meta']['contactList'], $this->get_key());
     $this->log_debug(__METHOD__ . '(): Adding subscriber => ' . print_r($subscriber, 1));
     $result = $api->add($subscriber);
     $this->log_debug(__METHOD__ . '(): Result => ' . print_r($result, true));
 }
Esempio n. 2
0
 public function changeSubscription(User $user, array $addLists, array $deleteLists)
 {
     $this->debugLog("changeSubscription: user #{$user->pk()}; added:" . json_encode($addLists) . "; deleted:" . json_encode($deleteLists));
     require_once 'lib/csrest_subscribers.php';
     if ($addLists) {
         $customFields = $this->getCustomFields($user);
     }
     foreach ($addLists as $listId) {
         $wrap = new CS_REST_Subscribers($listId, array('api_key' => $this->getConfig('api_key')));
         $result = $wrap->add(array('EmailAddress' => $user->email, 'Name' => $user->getName(), 'Resubscribe' => true));
         if (!empty($customFields)) {
             $result['CustomFields'] = $customFields;
         }
         if (!$result->was_successful()) {
             throw new Am_Exception_InternalError("Cannot subscribe user {$user->email} by reason: {$result->http_status_code}");
         }
     }
     foreach ($deleteLists as $listId) {
         $wrap = new CS_REST_Subscribers($listId, array('api_key' => $this->getConfig('api_key')));
         $result = $wrap->unsubscribe($user->email);
         if (!$result->was_successful()) {
             $this->debugLog("changeSubscription: unsubscribe user #{$user->pk()} failed:" . json_encode($result));
             throw new Am_Exception_InternalError("Cannot unsubscribe user {$user->email} by reason: {$result->http_status_code}");
         }
     }
     return true;
 }
Esempio n. 3
0
 public function add_subscriber($data = array())
 {
     require_once APPPATH . 'vendor/campaignmonitor/csrest_subscribers.php';
     $auth = array('api_key' => \Config::get('details.api_key'));
     $client_id = \Config::get('details.client_id');
     $list_id = \Config::get('details.list_id');
     $subscriber = new \CS_REST_Subscribers($list_id, $auth);
     return $subscriber->add($data);
 }
 public function indeed_campaignMonitor($listId, $apiID, $e_mail, $full_name = '')
 {
     require_once $this->dir_path . '/email_services/campaignmonitor/csrest_subscribers.php';
     $obj = new CS_REST_Subscribers($listId, $apiID);
     $args = array('EmailAddress' => $e_mail, 'Resubscribe' => true);
     if (!empty($full_name)) {
         $args['Name'] = $full_name;
     }
     $result = $obj->add($args);
     if ($result->was_successful()) {
         return 1;
     } else {
         return 0;
     }
 }
 public function add($listId, $email, $name = null, $customFields = array(), $resubscribe = true)
 {
     if (!$listId) {
         throw new Exception('List ID is required');
     }
     if (!$email) {
         throw new Exception('Please provide a valid email address');
     }
     $connection = new \CS_REST_Subscribers($listId, $this->auth());
     $result = $connection->add(['EmailAddress' => $email, 'Name' => $name, 'CustomFields' => $this->parseCustomFields($customFields), 'Resubscribe' => $resubscribe]);
     $error = null;
     if (!$this->response($result, $error)) {
         throw new Exception($error);
     }
     craft()->oneCampaignMonitor_log->subscription($listId, $email);
     return true;
 }
 /**
  * Subscribes to Campaign Monitor list. Returns either "success" string or error message.
  * @return string
  */
 function subscribe_campaign_monitor($api_key, $email, $list_id, $name = '')
 {
     require_once RAD_RAPIDOLOGY_PLUGIN_DIR . 'subscription/createsend-php-4.0.2/csrest_subscribers.php';
     $auth = array('api_key' => $api_key);
     $wrap = new CS_REST_Subscribers($list_id, $auth);
     $is_subscribed = $wrap->get($email);
     if ($is_subscribed->was_successful()) {
         $error_message = __('Already subscribed', 'rapidology');
     } else {
         $result = $wrap->add(array('EmailAddress' => $email, 'Name' => $name, 'Resubscribe' => false));
         if ($result->was_successful()) {
             $error_message = 'success';
         } else {
             $error_message = $result->response->message;
         }
     }
     return $error_message;
 }
 public static function donation_button_campaign_monitor_handler($posted)
 {
     $cm_api_key = get_option("campaignmonitor_api_key");
     $client_id = get_option("campaignmonitor_client_id");
     $cm_list_id = get_option("campaignmonitor_lists");
     $fname = isset($posted['first_name']) ? $posted['first_name'] : '';
     $lname = isset($posted['last_name']) ? $posted['last_name'] : '';
     $email = isset($posted['payer_email']) ? $posted['payer_email'] : $posted['receiver_email'];
     $debug = get_option('log_enable_campaignmonitor') == 'yes' ? 'yes' : 'no';
     if ('yes' == $debug) {
         $log = new Donation_Button_Logger();
     }
     if (isset($cm_api_key) && !empty($cm_api_key) && (isset($client_id) && !empty($client_id)) && (isset($cm_list_id) && !empty($cm_list_id))) {
         include_once DBP_PLUGIN_DIR_PATH . '/admin/partials/lib/campaign_monitor/csrest_subscribers.php';
         $wrap = new CS_REST_Subscribers($cm_list_id, $cm_api_key);
         try {
             $response = $wrap->get($email);
             if ($response->http_status_code == "200") {
                 $result = $wrap->update($email, array('EmailAddress' => $email, 'Name' => $fname . ' ' . $lname, 'CustomFields' => array(), 'Resubscribe' => true));
                 if ("yes" == $debug) {
                     if ($response->response->State == "Unsubscribed") {
                         $log->add('CampaignMonitor', ' CampaignMonitor new contact ' . $email . ' added to selected contact list');
                     } else {
                         $log->add('CampaignMonitor', ' CampaignMonitor update contact ' . $email . ' to selected contact list');
                     }
                 }
             } else {
                 $result = $wrap->add(array('EmailAddress' => $email, 'Name' => $fname . ' ' . $lname, 'CustomFields' => array(), 'Resubscribe' => true));
                 if (isset($result) && 'yes' == $debug) {
                     $log->add('CampaignMonitor', ' CampaignMonitor new contact ' . $email . ' added to selected contact list');
                 }
             }
         } catch (Exception $e) {
             if ('yes' == $debug) {
                 $log->add('CampaignMonitor', prin_r($e, true));
             }
         }
     } else {
         if ('yes' == $debug) {
             $log->add('CampaignMonitor', 'Campaign Monitor API Key OR Campaign Monitor Client ID does not set');
         }
     }
 }
 public static function cmdr_user_update($user_id, $args = null, $user_email = null, $new_user = false)
 {
     global $cmdr_fields_to_hide;
     $cmdr_user_fields = (array) unserialize(base64_decode(get_option('cmdr_user_fields')));
     if (!class_exists('CS_REST_Subscribers')) {
         require_once CMDR_PLUGIN_PATH . 'campaignmonitor-createsend-php/csrest_subscribers.php';
     }
     $auth = array('api_key' => get_option('cmdr_api_key'));
     $wrap_s = new CS_REST_Subscribers(get_option('cmdr_list_id'), $auth);
     $user = get_userdata($user_id);
     if (!$user) {
         return false;
     }
     if (!is_array($args)) {
         $args = array();
         $args['EmailAddress'] = $user->user_email;
         $args['Name'] = $user->first_name . ' ' . $user->last_name;
         foreach ($cmdr_user_fields as $key => $field) {
             if (!in_array($field, $cmdr_fields_to_hide)) {
                 if (is_scalar(get_user_meta($user->ID, $field, true))) {
                     $args['CustomFields'][] = array('Key' => $field, 'Value' => get_user_meta($user->ID, $field, true));
                 } else {
                     $args['CustomFields'][] = array('Key' => $field, 'Value' => '');
                 }
             }
         }
     }
     if (empty($user_email)) {
         $user_email = $user->user_email;
     }
     if (count($args)) {
         if ($new_user) {
             $result = $wrap_s->add($args);
         } else {
             $result = $wrap_s->update($user_email, $args);
         }
         if (!$result->was_successful()) {
             self::$error = $result->response;
             return false;
         }
     }
     return true;
 }
     if (!$list_v['updateexistingcontact']) {
         $cm_search_res = $wrap->get($campaignmonitor_contact['EmailAddress']);
         if ($contactform_obj->cfg['debug']) {
             echo 'SEARCH RESULTS ' . "\r\n";
             print_r($cm_search_res);
             echo "\r\n";
         }
     }
     /**
      * Error response 203 returns : Subscriber not in list or has already been removed.
      * Error response 203 : Email Address does not belong to the list. Subscriber not updated.
      * https://www.campaignmonitor.com/api/subscribers/#updating_a_subscriber
      */
     if (isset($cm_search_res) && isset($cm_search_res->response->Code) && $cm_search_res->response->Code == 203 || $list_v['updateexistingcontact']) {
         // If the subscriber (email address) already exists, their name and any custom field values are updated with whatever is passed in.
         $result = $wrap->add($campaignmonitor_contact);
         if ($contactform_obj->cfg['debug']) {
             echo 'ADD/UPDATE CONTACT' . "\r\n";
             print_r($result);
         }
         if (!$result->was_successful()) {
             if (isset($result->response->Code)) {
                 $admin_api_error[$service_id]['error_code'] = $result->response->Code;
             }
             if (!isset($result->response->Code) && $result->http_status_code == '400') {
                 $admin_api_error[$service_id]['error_code'] = $result->http_status_code;
             }
         }
     }
 }
 // if fields
Esempio n. 10
0
<?php

require_once '../../csrest_subscribers.php';
$wrap = new CS_REST_Subscribers('Your list ID', 'Your API Key');
$result = $wrap->add(array('EmailAddress' => 'Subscriber email', 'Name' => 'Subscriber name', 'CustomFields' => array(array('Key' => 'Field Key', 'Value' => 'Field Value')), 'Resubscribe' => true));
echo "Result of POST /api/v3/subscribers/{list id}.{format}\n<br />";
if ($result->was_successful()) {
    echo "Subscribed with code " . $result->http_status_code;
} else {
    echo 'Failed with code ' . $result->http_status_code . "\n<br /><pre>";
    var_dump($result->response);
    echo '</pre>';
}
Esempio n. 11
0
            $use_array = $toll_array;
            $has_toll = 1;
        }
        if ($mail_now !== 0) {
            $status = requestInfo($title, $use_email, $use_array, $cc);
        }
    }
    if (!$builders) {
        $has_toll = 1;
        //generate_xml_email_kb();
    }
    //Add to campaign monitor
    if (isset($subscribe) && $subscribe == 'subscribe') {
        $auth = array('api_key' => 'b76726b5487a8012d8dadf7fbde197ec');
        $wrap = new CS_REST_Subscribers('af089ef176d2e472fae6c01c312eda7f', $auth);
        $result = $wrap->add(array('EmailAddress' => trim($_POST['email']), 'Name' => stripslashes($_POST['firstName']) . ' ' . stripslashes($_POST['lastName']), 'Resubscribe' => true));
    }
    print_r(json_encode(array('status' => $status, 'interested_models' => $requested_properties, 'builders' => $builders, 'firstName' => $_POST['firstName'], 'lastName' => $_POST['lastName'], 'community' => $community_number, 'email' => $_POST['email'], 'comment' => $_POST['comment'], 'phone' => $_POST['phone'])));
    // Store in DB
    $wpdb->insert('ap_leads', array('first' => stripslashes($_POST['firstName']), 'last' => stripslashes($_POST['lastName']), 'email' => trim($_POST['email']), 'phone' => trim($_POST['phone']), 'comment' => trim($_POST['comment']), 'builders' => isset($_POST['builders']) ? json_encode($_POST['builders']) : '', 'properties' => json_encode($property_ids)));
} else {
    if ($_POST['type'] === 'toll') {
        //print_r(generate_xml_soap_toll());
    } else {
        // Filter Results
        $price_min = $_POST['price_min'] ? $_POST['price_min'] : 0;
        $price_max = $_POST['price_max'] ? $_POST['price_max'] : 999999999;
        $beds = $_POST['beds'] ? $_POST['beds'] : 0;
        $builder = !$_POST['builder'] ? false : $_POST['builder'];
        $stories = $_POST['stories'] === 0 ? false : $_POST['stories'];
        $sq_ft = $_POST['sq_ft'] ? $_POST['sq_ft'] : 0;
 /**
  * Processes integration with 3rd party APIs.
  * @param cf_Contest $contest
  * @param cf_Participant $participant
  */
 static function process_integration($contest, $participant)
 {
     // mailing lists
     $email = $participant->email;
     $name = '';
     $first_name = '';
     $last_name = '';
     if ($contest->cf_name_field == '1') {
         $name = $participant->first_name . ' ' . $participant->last_name;
         $first_name = $participant->first_name;
         $last_name = $participant->last_name;
     }
     if ($contest->cf_participants_export == 'campaignmonitor') {
         if (!class_exists(CS_REST_Subscribers)) {
             require cf_Manager::$plugin_dir . 'lib/campaign_monitor/csrest_subscribers.php';
         }
         $wrap = new CS_REST_Subscribers($contest->cf_campaignmonitor_list, $contest->cf_campaignmonitor_key);
         $res = $wrap->add(array('EmailAddress' => $email, 'Name' => $name, 'Resubscribe' => true));
         // $res->was_successful()
         // $res->http_status_code
         // $res->response
     } else {
         if ($contest->cf_participants_export == 'mailchimp') {
             if (!class_exists(MCAPI)) {
                 require cf_Manager::$plugin_dir . 'lib/MCAPI.class.php';
             }
             $double_optin = true;
             if ($contest->cf_double_optin == '1') {
                 $double_optin = false;
             }
             $api = new MCAPI($contest->cf_mailchimp_key);
             $api->listSubscribe($contest->cf_mailchimp_list, $email, array('FNAME' => $first_name, 'LNAME' => $last_name), 'html', $double_optin);
             // double optin;
             // if($api->errorCode)
             // $api->errorCode
             // $api->errorMessage
         } else {
             if ($contest->cf_participants_export == 'getresponse') {
                 require cf_Manager::$plugin_dir . 'lib/GetResponseAPI.class.php';
                 $api = new GetResponseAPI($contest->cf_getresponse_key);
                 $response = $api->addContact($contest->cf_getresponse_list, $name, $email);
                 // var_dump($response);
             } else {
                 if ($contest->cf_participants_export == 'aweber') {
                     require cf_Manager::$plugin_dir . 'lib/aweber/aweber_api.php';
                     $aweber_auth = $contest->cf_aweber_auth;
                     if (!empty($aweber_auth) && is_array($aweber_auth)) {
                         $api = new AWeberAPI($aweber_auth['consumer_key'], $aweber_auth['consumer_secret']);
                         try {
                             $account = $api->getAccount($aweber_auth['access_key'], $aweber_auth['access_secret']);
                             $listURL = "/accounts/{$account->id}/lists/{$contest->cf_aweber_list}";
                             $list = $account->loadFromUrl($listURL);
                             // create a subscriber
                             $params = array('email' => $email, 'ip_address' => $_SERVER['REMOTE_ADDR'], 'name' => $name);
                             $subscribers = $list->subscribers;
                             $new_subscriber = $subscribers->create($params);
                         } catch (AWeberAPIException $exc) {
                             // TODO log (post comments?)
                         }
                     }
                 }
             }
         }
     }
     do_action('cf_process_integration', $contest, $participant);
 }
Esempio n. 13
0
 public static function export_feed($entry, $form, $feed)
 {
     $resubscribe = $feed["meta"]["resubscribe"] ? true : false;
     $email = $entry[$feed["meta"]["field_map"]["email"]];
     $name = "";
     if (!empty($feed["meta"]["field_map"]["fullname"])) {
         $name = self::get_name($entry, $feed["meta"]["field_map"]["fullname"]);
     }
     $merge_vars = array();
     foreach ($feed["meta"]["field_map"] as $var_key => $field_id) {
         if (!in_array($var_key, array('email', 'fullname'))) {
             $merge_vars[] = array("Key" => $var_key, "Value" => $entry[$field_id]);
         }
     }
     $subscriber = array('EmailAddress' => $email, 'Name' => $name, 'CustomFields' => $merge_vars, 'Resubscribe' => $resubscribe);
     $api = new CS_REST_Subscribers($feed["meta"]["contact_list_id"], self::get_api_key());
     $api->add($subscriber);
 }
Esempio n. 14
0
<?php

require_once 'campaign-monitor/csrest_subscribers.php';
$apiKey = '';
// Your MailChimp API Key
$listId = '';
// Your MailChimp List ID
if (isset($_GET['list']) and $_GET['list'] != '') {
    $listId = $_GET['list'];
}
$email = $_POST['widget-subscribe-form-email'];
if (isset($email) and $email != '') {
    $auth = array('api_key' => $apiKey);
    $wrap = new CS_REST_Subscribers($listId, $auth);
    $result = $wrap->add(array('EmailAddress' => $email, 'Resubscribe' => true));
    if ($result->was_successful()) {
        echo '{ "alert": "success", "message": "You have been <strong>successfully</strong> subscribed to our Email List." }';
    } else {
        echo '{ "alert": "error", "message": "Failed with code ' . $result->http_status_code . "\n<br /><pre>";
        var_dump($result->response);
        echo '</pre>" }';
    }
}
function sendCompaingMonitor($mailSubscribe)
{
    if (defined('CM_APIKEY') && defined('CM_LISTID')) {
        $wrap = new CS_REST_Subscribers(CM_LISTID, array('api_key' => CM_APIKEY));
        $result = $wrap->add(array('EmailAddress' => $mailSubscribe, 'Resubscribe' => true));
        if (!$result->was_successful()) {
            throw new Exception("Error found Lists", 4);
        }
    }
}
 public function newAction()
 {
     if ($this->getRequest()->isPost() && $this->getRequest()->getPost('email')) {
         $session = Mage::getSingleton('core/session');
         $email = (string) $this->getRequest()->getPost('email');
         Mage::log("DigitalPianism_CampaignMonitor: Adding newsletter subscription via frontend 'Sign up' block for {$email}");
         if (Mage::helper('campaignmonitor')->isOAuth()) {
             $accessToken = Mage::getModel('campaignmonitor/auth')->getAccessToken();
             $refreshToken = Mage::getModel('campaignmonitor/auth')->getRefreshToken();
             $auth = array('access_token' => $accessToken, 'refresh_token' => $refreshToken);
         } else {
             $auth = Mage::helper('campaignmonitor')->getApiKey();
         }
         $listID = Mage::helper('campaignmonitor')->getListId();
         if ($auth && $listID) {
             try {
                 $client = new CS_REST_Subscribers($listID, $auth);
             } catch (Exception $e) {
                 Mage::helper('campaignmonitor')->log("Error connecting to CampaignMonitor server: " . $e->getMessage());
                 $session->addException($e, $this->__('There was a problem with the subscription'));
                 $this->_redirectReferer();
             }
             // if a user is logged in, fill in the Campaign Monitor custom
             // attributes with the data for the logged-in user
             $customerHelper = Mage::helper('customer');
             if ($customerHelper->isLoggedIn()) {
                 $customer = $customerHelper->getCustomer();
                 $name = $customer->getFirstname() . " " . $customer->getLastname();
                 $customFields = Mage::helper('campaignmonitor')->generateCustomFields($customer);
                 try {
                     $result = $client->add(array("EmailAddress" => $email, "Name" => $name, "CustomFields" => $customFields, "Resubscribe" => true));
                     if (!$result->was_successful()) {
                         // If you receive '121: Expired OAuth Token', refresh the access token
                         if ($result->response->Code == 121) {
                             // Refresh the token
                             Mage::helper('campaignmonitor')->refreshToken();
                         }
                         // Make the call again
                         $client->add(array("EmailAddress" => $email, "Name" => $name, "CustomFields" => $customFields, "Resubscribe" => true));
                     }
                 } catch (Exception $e) {
                     Mage::helper('campaignmonitor')->log("Error in CampaignMonitor SOAP call: " . $e->getMessage());
                     $session->addException($e, $this->__('There was a problem with the subscription'));
                     $this->_redirectReferer();
                 }
             } else {
                 // otherwise if nobody's logged in, ignore the custom
                 // attributes and just set the name to '(Guest)'
                 try {
                     $result = $client->add(array("EmailAddress" => $email, "Name" => "(Guest)", "Resubscribe" => true));
                     if (!$result->was_successful()) {
                         // If you receive '121: Expired OAuth Token', refresh the access token
                         if ($result->response->Code == 121) {
                             // Refresh the token
                             Mage::helper('campaignmonitor')->refreshToken();
                         }
                         // Make the call again
                         $client->add(array("EmailAddress" => $email, "Name" => "(Guest)", "Resubscribe" => true));
                     }
                 } catch (Exception $e) {
                     Mage::helper('campaignmonitor')->log("Error in CampaignMonitor SOAP call: " . $e->getMessage());
                     $session->addException($e, $this->__('There was a problem with the subscription'));
                     $this->_redirectReferer();
                 }
             }
         } else {
             Mage::helper('campaignmonitor')->log("Error: Campaign Monitor API key and/or list ID not set in Magento Newsletter options.");
         }
     }
     parent::newAction();
 }
 /**
  * @return Boolean/Result
  */
 public function getValueFromData($data)
 {
     // if this field was set and there are lists - subscriper the user
     if (isset($data[$this->Name]) && $this->getLists()->Count() > 0) {
         $this->extend('beforeValueFromData', $data);
         require_once '../vendor/campaignmonitor/createsend-php/csrest_subscribers.php';
         $auth = array(null, 'api_key' => $this->config()->get('api_key'));
         $wrap = new CS_REST_Subscribers($this->getField('ListID'), $auth);
         $result = $wrap->add(array('EmailAddress' => $data[$this->getField('EmailField')], 'Name' => $data[$this->getField('FirstNameField')] . ' ' . $data[$this->getField('LastNameField')], 'Resubscribe' => true));
         $this->extend('afterValueFromData', $result);
         if ($result->was_successful()) {
             return "Subscribed with code " . $result->http_status_code;
         } else {
             return "Not subscribed with code " . $result->http_status_code;
         }
     }
     return false;
 }
Esempio n. 18
0
 /**
  * Subscribe a customer who subscribed to Mage after a successfull registration
  * @param $observer
  */
 public function subscribeCustomer(Varien_Event_Observer $observer)
 {
     // Get the customer
     $customer = $observer->getEvent()->getCustomer();
     // Get its email
     $email = $customer->getEmail();
     $name = $customer->getFirstname() . " " . $customer->getLastname();
     // Check if subscribed
     $hasSubscribed = $customer->getIsSubscribed();
     if (Mage::helper('campaignmonitor')->isOAuth()) {
         $accessToken = Mage::getModel('campaignmonitor/auth')->getAccessToken();
         $refreshToken = Mage::getModel('campaignmonitor/auth')->getRefreshToken();
         $auth = array('access_token' => $accessToken, 'refresh_token' => $refreshToken);
     } else {
         $auth = Mage::helper('campaignmonitor')->getApiKey();
     }
     $listID = Mage::helper('campaignmonitor')->getListId();
     // Check if the customer has subscribed via OG magento checkbox
     if ($hasSubscribed) {
         $customFields = Mage::helper('campaignmonitor')->generateCustomFields($customer);
         // Using 'add and resubscribe' rather than just 'add', otherwise
         // somebody who unsubscribes and resubscribes won't be put back
         // on the active list
         Mage::helper('campaignmonitor')->log("Subscribing new email address: {$newEmail}");
         try {
             $client = new CS_REST_Subscribers($listID, $auth);
             $result = $client->add(array("EmailAddress" => $email, "Name" => $name, "CustomFields" => $customFields, "Resubscribe" => true));
             if (!$result->was_successful()) {
                 // If you receive '121: Expired OAuth Token', refresh the access token
                 if ($result->response->Code == 121) {
                     // Refresh the token
                     Mage::helper('campaignmonitor')->refreshToken();
                 }
                 // Make the call again
                 $client->add(array("EmailAddress" => $email, "Name" => $name, "CustomFields" => $customFields, "Resubscribe" => true));
             }
         } catch (Exception $e) {
             Mage::helper('campaignmonitor')->log("Error in SOAP call: " . $e->getMessage());
             return;
         }
     }
 }
 public function email_list_add($name)
 {
     error_log("EM: email_list_add", 0);
     $wrap = new CS_REST_Subscribers(CM_MEMBERLIST, CM_APIKEY);
     // future (if grind supports multiple emails per person you will need
     // to ensure this is a primary email that you are adding
     $result = $wrap->add(array('EmailAddress' => $this->email->address, 'Name' => $name, 'CustomFields' => array(array('Key' => 'grind_id', 'Value' => $this->email->user_id)), 'Resubscribe' => true));
     if ($result->was_successful()) {
         error_log("Subscribed with code " . $result->http_status_code, 0);
         return true;
     } else {
         error_log('Failed with code ' . $result->http_status_code . "\n<br /><pre>", 0);
         return false;
     }
 }
        $output .= "},";
    }
    //subs the last comma
    $output = substr($output, 0, -1);
    $output .= "]";
    echo $output;
} elseif ($req == "addSub" && isset($_GET["list_id"])) {
    //Add a new subscriber to the list
    $list_id = $_GET["list_id"];
    //Save the data that were posted by the client via ajax
    $name = $_POST["Name"];
    $email = $_POST["EmailAddress"];
    //array manipiulation of the input parameters for the API method
    $subscriber = array("EmailAddress" => $email, "Name" => $name);
    //Get the appropriate wrapper to add a new subscriber
    $wrap_subscribers = new CS_REST_Subscribers($list_id, $auth);
    $add_subsciber = $wrap_subscribers->add($subscriber);
} elseif ($req == "removSub" && isset($_GET["list_id"])) {
    //remove a subscriber
    $list_id = $_GET["list_id"];
    //Email is needed as an input parameter for API method
    $email = $_POST["EmailAddress"];
    //Get the appropriate wrapper to remove a subscriber
    $wrap_subscribers = new CS_REST_Subscribers($list_id, $auth);
    $remove_subscriber = $wrap_subscribers->unsubscribe($email);
} else {
    echo "Please check the AJAX url";
}
?>

Esempio n. 21
0
File: CRM.php Progetto: zehash/ff
 public function signup($user, $member)
 {
     // Campaign Monitor
     $cm_details = Config::get('services.campaignmonitor');
     $campaignmonitor = new CS_REST_Subscribers($cm_details['list_id'], $cm_details['auth_details']);
     $result = $campaignmonitor->add(array('EmailAddress' => $user->email, 'Name' => $member->firstname . ' ' . $member->lastname, 'CustomFields' => array(), 'Resubscribe' => false));
     // Boxever
     $keys = "?client_key=mz5gfrJyaUcG4Pc2uugPhupj3KRV5kMt&api_token=ADvnoiQ4HJsgzt5479ltfu77Z6pTCweO&";
     $res = $this->curlGet('https://api.boxever.com/v1.2/customer/search.json' . $keys . "email=" . $user->email);
     $dobISO = new DateTime($member->dob);
     $nowISO = new DateTime();
     $message = array('first_name' => $member->firstname, 'lastname' => $member->lastname, 'dob' => $dobISO->format(DateTime::ISO8601), 'email' => $user->email, 'phone' => $member->phone, 'address' => $member->address, 'postcode' => $member->postcode, 'state' => $member->state, 'tiff_has_flown' => $member->hasflown == 'y' ? true : false, 'tiff_flights_per_year' => $member->flightsperyear, 'tiff_member' => true, 'subscriptions' => array(array('name' => "infrequent_flyers", 'pos' => "default", 'medium' => "EMAIL", 'status' => "SUBSCRIBED", 'effectiveDate' => urlencode($nowISO->format(DateTime::ISO8601)))));
     foreach ($message as $key => $val) {
         if (gettype($val) === 'string') {
             $message[$key] = urlencode($val);
         }
     }
     // Upload to SFTP server
     $dstFile = "iff_data_production/{$member->id}.json";
     $fileContents = json_encode($message);
     // set up basic connection
     $domain = "sftp.tiger.jba-processing.com";
     try {
         $sftp = new Net_SFTP($domain);
         // Turn on logging
         define('NET_SFTP_LOGGING', NET_SFTP_LOG_COMPLEX);
         // Attempt login
         if ($sftp->login('tiger_mccann', 'fsJcBsuepHMVrYrY')) {
             // Attempt upload
             $i = 0;
             do {
                 $sftp->put($dstFile, $fileContents);
             } while ($sftp->size($dstFile) === false && ++$i < 5);
         } else {
             Log::error("SFTP Login failed");
         }
     } catch (Exception $e) {
         Log::error($e);
     }
     Log::error($sftp->getSFTPLog());
     // No longer sending to Boxever
     /*
         if ($res->status == 'OK' && !isset($res->customer_ref)) {
      // Customer doesn't exist, create new customer
      //
      // Boxever doesn't seem to return a customer_ref even if the customer exists...
      // So we'll attempt to add it, and if it fails, then the user already exists in our list.
     
      $message['customer_id'] = urlencode($user->email);
     
      $message = json_encode($message);
     
      $res = $this->curlGet('https://api.boxever.com/v1.2/customer/create.json' . $keys . 'message=' . $message );
     
         } else if (isset($res->customer_ref)) {
      // Customer exists, update their data
      $message = json_encode($message);
      
      $res = $this->curlGet('https://api.boxever.com/v1.2/customer/'.$res->customer_ref[0].'/update.json' . $keys . 'message=' . $message);
     
         } else {
      // Initial resource request failed
      $boxever = 'API Failed';
         }
     */
     return $res;
 }
Esempio n. 22
0
 public function makeCampaignmonitorEntry($user_id)
 {
     $email = userpro_profile_data('user_email', $user_id);
     include userpro_path . 'lib/campaignmonitor/csrest_subscribers.php';
     $list_id = userpro_get_option('Campaignmonitor_listname');
     $auth_details = array('api_key' => userpro_get_option('Campaignmonitor_api'));
     $api = new CS_REST_Subscribers($list_id, $auth_details);
     $subscriber = array('EmailAddress' => $email);
     $api->add($subscriber);
 }
Esempio n. 23
0
<?php

require_once '../../csrest_subscribers.php';
$auth = array('access_token' => 'your access token', 'refresh_token' => 'your refresh token');
$wrap = new CS_REST_Subscribers('Your list ID', $auth);
$result = $wrap->add(array('EmailAddress' => 'Subscriber email', 'Name' => 'Subscriber name', 'CustomFields' => array(array('Key' => 'Field 1 Key', 'Value' => 'Field Value'), array('Key' => 'Field 2 Key', 'Value' => 'Field Value'), array('Key' => 'Multi Option Field 1', 'Value' => 'Option 1'), array('Key' => 'Multi Option Field 1', 'Value' => 'Option 2')), 'Resubscribe' => true));
echo "Result of POST /api/v3.1/subscribers/{list id}.{format}\n<br />";
if ($result->was_successful()) {
    echo "Subscribed with code " . $result->http_status_code;
} else {
    echo 'Failed with code ' . $result->http_status_code . "\n<br /><pre>";
    var_dump($result->response);
    echo '</pre>';
}
Esempio n. 24
0
 /**
  * @param $observer
  */
 public function subscribeCustomer($observer)
 {
     // Check if the checkbox has been ticked using the sessions
     if ((bool) Mage::getSingleton('checkout/session')->getCustomerIsSubscribed()) {
         // Get the quote & customer
         $quote = $observer->getEvent()->getQuote();
         $order = $observer->getEvent()->getOrder();
         // if (!$order->getCustomerIsGuest()) return;
         // Mage::helper('campaignmonitor')->log('passed');
         $session = Mage::getSingleton('core/session');
         // Get the email using during checking out
         $email = $order->getCustomerEmail();
         // We get the API and List ID
         if (Mage::helper('campaignmonitor')->isOAuth()) {
             $accessToken = Mage::getModel('campaignmonitor/auth')->getAccessToken();
             $refreshToken = Mage::getModel('campaignmonitor/auth')->getRefreshToken();
             $auth = array('access_token' => $accessToken, 'refresh_token' => $refreshToken);
         } else {
             $auth = Mage::helper('campaignmonitor')->getApiKey();
         }
         $listID = Mage::helper('campaignmonitor')->getListId();
         $apiKey = Mage::helper('campaignmonitor')->getApiKey();
         // Check if already susbcribed
         try {
             $client = new CS_REST_Subscribers($listID, $auth);
             $result = $client->get($email);
             if (!$result->was_successful()) {
                 // If you receive '121: Expired OAuth Token', refresh the access token
                 if ($result->response->Code == 121) {
                     // Refresh the token
                     Mage::helper('campaignmonitor')->refreshToken();
                 }
                 // Make the call again
                 $result = $client->get($email);
             }
         } catch (Exception $e) {
             Mage::helper('campaignmonitor')->log("Error in REST call: " . $e->getMessage());
             $session->addException($e, Mage::helper('campaignmonitor')->__('There was a problem with the subscription'));
         }
         // If we are not subscribed in Campaign Monitor
         if ($result->was_successful() && $result->response->State != 'Active') {
             // We generate the custom fields
             if ($mobile = $quote->getBillingAddress()->getTelephone()) {
                 $customFields[] = array("Key" => "Mobile", "Value" => $mobile);
             }
             $state = $quote->getBillingAddress()->getRegion();
             $country = $quote->getBillingAddress()->getCountryId();
             if ($state || $country) {
                 $campaignMonitorStates = Mage::helper('campaignmonitor')->getCampaignMonitorStates();
                 if ($country == "AU" && in_array($state, $campaignMonitorStates)) {
                     $customFields[] = array("Key" => "State", "Value" => $state);
                 } elseif ($country == "NZ") {
                     $customFields[] = array("Key" => "State", "Value" => "New Zealand");
                 } elseif ($country) {
                     $customFields[] = array("Key" => "State", "Value" => "Other");
                 } else {
                     $customFields[] = array("Key" => "State", "Value" => "Unknown");
                 }
             } else {
                 $customFields[] = array("Key" => "State", "Value" => "Unknown");
             }
             if ($postcode = $quote->getBillingAddress()->getPostcode()) {
                 $customFields[] = array("Key" => "Postcode", "Value" => $postcode);
             }
             if ($dob = $quote->getCustomerDob()) {
                 $customFields[] = array("Key" => "DOB", "Value" => $dob);
             }
             // And generate the hash
             $customFields[] = array("Key" => "securehash", "Value" => md5($email . $apiKey));
             // We generate the Magento fields
             $fullname = $quote->getBillingAddress()->getName();
             $fullname = trim($fullname);
             $customFields[] = array("Key" => "fullname", "Value" => $fullname);
             // Check the checkout method (logged in, register or guest)
             switch ($quote->getCheckoutMethod()) {
                 // Customer is logged in
                 case Mage_Sales_Model_Quote::CHECKOUT_METHOD_LOGIN_IN:
                     // Customer is registering
                 // Customer is registering
                 case Mage_Sales_Model_Quote::CHECKOUT_METHOD_REGISTER:
                     // Customer is a guest
                 // Customer is a guest
                 case Mage_Sales_Model_Quote::CHECKOUT_METHOD_GUEST:
                     try {
                         // Subscribe the customer to CampaignMonitor
                         if ($client) {
                             $result = $client->add(array("EmailAddress" => $email, "Name" => $fullname, "CustomFields" => $customFields, "Resubscribe" => true));
                             if (!$result->was_successful()) {
                                 // If you receive '121: Expired OAuth Token', refresh the access token
                                 if ($result->response->Code == 121) {
                                     // Refresh the token
                                     Mage::helper('campaignmonitor')->refreshToken();
                                 }
                                 // Make the call again
                                 $client->add(array("EmailAddress" => $email, "Name" => $fullname, "CustomFields" => $customFields, "Resubscribe" => true));
                             }
                         }
                     } catch (Exception $e) {
                         Mage::helper('campaignmonitor')->log("Error in CampaignMonitor REST call: " . $e->getMessage());
                         $session->addException($e, Mage::helper('campaignmonitor')->__('There was a problem with the subscription'));
                     }
                     break;
             }
         }
         // Remove the session variable
         Mage::getSingleton('checkout/session')->setCustomerIsSubscribed(0);
         Mage::getModel('campaignmonitor/subscriber')->syncSubscriber($email, true);
     }
 }
Esempio n. 25
0
 public static function export_feed($entry, $form, $feed)
 {
     $resubscribe = $feed["meta"]["resubscribe"] ? true : false;
     $email = $entry[$feed["meta"]["field_map"]["email"]];
     $name = "";
     if (!empty($feed["meta"]["field_map"]["fullname"])) {
         $name = self::get_name($entry, $feed["meta"]["field_map"]["fullname"]);
     }
     $merge_vars = array();
     foreach ($feed["meta"]["field_map"] as $var_key => $field_id) {
         $field = RGFormsModel::get_field($form, $field_id);
         if (GFCommon::is_product_field($field["type"]) && rgar($field, "enablePrice")) {
             $ary = explode("|", $entry[$field_id]);
             $name = count($ary) > 0 ? $ary[0] : "";
             $merge_vars[] = array("Key" => $var_key, "Value" => $name);
         } else {
             if (RGFormsModel::get_input_type($field) == "checkbox") {
                 foreach ($field["inputs"] as $input) {
                     $index = (string) $input["id"];
                     if (!rgempty($index, $entry)) {
                         $merge_vars[] = array("Key" => $var_key, "Value" => $entry[$index]);
                     }
                 }
             } else {
                 if (!in_array($var_key, array('email', 'fullname'))) {
                     $merge_vars[] = array("Key" => $var_key, "Value" => $entry[$field_id]);
                 }
             }
         }
     }
     $subscriber = array('EmailAddress' => $email, 'Name' => $name, 'CustomFields' => $merge_vars, 'Resubscribe' => $resubscribe);
     $api = new CS_REST_Subscribers($feed["meta"]["contact_list_id"], self::get_api_key());
     $api->add($subscriber);
 }
Esempio n. 26
0
    /**
	 * Ajax newsletter
	 *
	 * @since    1.0.0
	 */
	public function ajax_subscribe() {

		// No First Name
		if (!isset($_POST['first_name'])) {
			$_POST['first_name'] = '';
		}

		// No Last Name
		if (!isset($_POST['last_name'])) {
			$_POST['last_name'] = '';
		}

		$success_message = stripcslashes( $this->settings['subscribe']['success_message'] );

		// MailChimp
		if ($_POST['type'] == 'mailchimp') {

			require_once('includes/mailchimp/MailChimp.php');

			if (!isset($this->settings['subscribe']['mailchimp']['api_key']) || $this->settings['subscribe']['mailchimp']['api_key'] == '') {
				echo json_encode(array(
					'status'	=> 'warning',
					'message'	=> __('MailChimp account is not setup properly.'),
				));

				die();
			}

			if (!isset($this->settings['subscribe']['mailchimp']['list']) || $this->settings['subscribe']['mailchimp']['list'] == '') {
				echo json_encode(array(
					'status'	=> 'warning',
					'message'	=> __('MailChimp: No list specified.'),
				));

				die();
			}

			$MailChimp = new WPS_MailChimp($this->settings['subscribe']['mailchimp']['api_key']);
			$result = $MailChimp->call('lists/subscribe', array(
                'id'                => $this->settings['subscribe']['mailchimp']['list'],
                'email'             => array('email'=>sanitize_email( $_POST['email']) ),
                'merge_vars'        => array( 'FNAME'=> sanitize_text_field( $_POST['first_name'] ), 'LNAME'=>sanitize_text_field( $_POST['last_name'] ) ),
                'double_optin'      => true,
                'update_existing'   => false,
                'replace_interests' => false,
                'send_welcome'      => true,
            ));

            if ($result) {

	            if (isset($result['email'])) {

					echo json_encode(array(
						'status'		=> 'check',
						'message'		=> $success_message,
					));

					die();
	            }

	            else if (isset($result['status']) && $result['status'] == 'error') {
					echo json_encode(array(
						'status'		=> 'warning',
						'message'		=> $result['error'],
					));

					die();
	            }
            } else {

	            echo json_encode(array(
					'status'	=> 'warning',
					'message'	=> __('Unable to subscribe.'),
				));

				die();
            }
		}

		// Add email to aweber
		else if ($_POST['type'] == 'aweber') {

			require_once('includes/aweber/aweber_api.php');

			if (!isset($this->settings['subscribe']['aweber']['consumer_key']) || $this->settings['subscribe']['aweber']['consumer_key'] == '') {
				echo json_encode(array(
					'status'	=> 'warning',
					'message'	=> __('Aweber account is not setup properly'),
				));

				die();
			}

			$aweber = new AWeberAPI($this->settings['subscribe']['aweber']['consumer_key'], $this->settings['subscribe']['aweber']['consumer_secret']);

			try {
				$account = $aweber->getAccount($this->settings['subscribe']['aweber']['access_key'], $this->settings['subscribe']['aweber']['access_secret']);
				$list = $account->loadFromUrl('/accounts/' . $account->id . '/lists/' . $this->settings['subscribe']['aweber']['list']);

				$subscriber = array(
					'email' 	=> sanitize_email( $_POST['email'] ),
					'name'		=> sanitize_text_field( $_POST['first_name'] ) . ' ' . sanitize_text_field( $_POST['last_name'] ),
					'ip' 		=> $_SERVER['REMOTE_ADDR']
				);

				$newSubscriber = $list->subscribers->create($subscriber);

				echo json_encode(array(
					'status'		=> 'check',
					'message'		=> $success_message,
				));

				die();

			} catch (AWeberAPIException $exc) {
				echo json_encode(array(
					'status'	=> 'warning',
					'message'	=> $exc->message,
				));

				die();
			}
		}

		// Add email to Get Response
		else if ($_POST['type'] == 'getresponse') {

			require_once('includes/getresponse/jsonRPCClient.php');

			$api = new jsonRPCClient('http://api2.getresponse.com');

			try {
				$api->add_contact(
					$this->settings['subscribe']['getresponse']['api_key'],
				    array (
				        'campaign'  => $this->settings['subscribe']['getresponse']['campaign'],
				        'name'      => sanitize_text_field( $_POST['first_name'] ) . ' ' . sanitize_text_field( $_POST['last_name'] ),
				        'email'     => sanitize_email( $_POST['email'] ),
				    )
				);

				echo json_encode(array(
					'status'		=> 'check',
					'message'		=> $success_message,
				));

				die();

			} catch (RuntimeException $exc) {

				$msg = $exc->getMessage();
				$msg = substr($msg, 0, strpos($msg, ";"));

				echo json_encode(array(
					'status'	=> 'warning',
					'message'	=> $msg,
				));

				die();
			}
		}

		// Add email to Campaign Monitor
		else if ($_POST['type'] == 'campaignmonitor') {

			require_once('includes/campaignmonitor/csrest_subscribers.php');

			$wrap = new CS_REST_Subscribers($this->settings['subscribe']['campaignmonitor']['list'], $this->settings['subscribe']['campaignmonitor']['api_key']);

			// Check if subscribor is already subscribed

			$result = $wrap->get(sanitize_email( $_POST['email'] ));

			if ($result->was_successful()) {
				echo json_encode(array(
					'status'	=> 'warning',
					'message'	=> 'You are already subscribed to this list.',
				));

				die();
			}

			$result = $wrap->add(array(
				'EmailAddress' 	=> sanitize_email($_POST['email']),
				'Name' 			=> sanitize_text_field( $_POST['first_name'] ). ' ' . sanitize_text_field( $_POST['last_name'] ),
				'Resubscribe' 	=> true
			));

			if ($result->was_successful()) {

				echo json_encode(array(
					'status'		=> 'check',
					'message'		=> $success_message,
				));

				die();

			} else {

				echo json_encode(array(
					'status'	=> 'warning',
					'message'	=> $result->response->Message,
				));

				die();
			}
		}

		// Add email to Mad Mimi
		else if ($_POST['type'] == 'madmimi') {

			require_once('includes/madmimi/MadMimi.class.php');

			$mailer = new MadMimi($this->settings['subscribe']['madmimi']['username'], $this->settings['subscribe']['madmimi']['api_key']);

			// No Email

			if (!isset($_POST['email']) || $_POST['email'] == '') {
				echo json_encode(array(
					'status'	=> 'warning',
					'message'	=> 'No Email address provided.'
				));
				die();
			}

			// Invalid Email Address

			if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
				echo json_encode(array(
					'status'	=> 'warning',
					'message'	=> 'Invalid Email provided.'
				));
				die();
			}

			try {

				// Check if user is already in list

				$result = $mailer->Memberships(sanitize_email( $_POST['email']) );
				$lists  = new SimpleXMLElement($result);

				if ($lists->list) {
					foreach ($lists->list as $l) {
						if ($l->attributes()->{'name'}->{0} == $meta_values['madmimi_list']) {

							echo json_encode(array(
								'status'		=> 'check',
								'message'		=> 'You are already subscribed to this list.',
							));

							die();
						}
					}
			    }

				$result = $mailer->AddMembership($this->settings['subscribe']['madmimi']['list'], sanitize_email( $_POST['email'] ), array(
					'first_name'	=> sanitize_text_field( $_POST['first_name'] ),
					'last_name'		=> sanitize_text_field( $_POST['last_name'] ),
				));

				echo json_encode(array(
					'status'		=> 'check',
					'message'		=> $success_message,
				));

				die();

			} catch (RuntimeException $exc) {

				echo json_encode(array(
					'status'	=> 'warning',
					'message'	=> $msg,
				));

				die();
			}
		}

		die();
	}
 /**
  * Record an impression made by a optin fire
  * This function is called via PHP.
  *
  * @access public
  * @static
  * @return void
  */
 function nnr_new_int_add_email_v1()
 {
     do_action('nnr_news_int_before_submission_add_email_v1');
     // No First Name
     if (!isset($_POST['first_name'])) {
         $_POST['first_name'] = '';
     }
     // No Last Name
     if (!isset($_POST['last_name'])) {
         $_POST['last_name'] = '';
     }
     // Could not find Data ID
     if (!isset($_POST['data_id']) || $_POST['data_id'] == '') {
         echo json_encode(array('id' => $_POST['data_id'], 'status' => 'warning', 'message' => __('Could not find Data ID.', $_POST['text_domain'])));
         die;
     }
     // Get all newsletter data for this data instance
     $data_manager = new NNR_Data_Manager_v1($_POST['table_name']);
     $data_instance = $data_manager->get_data_from_id($_POST['data_id']);
     $success_action = isset($data_instance['args']['newsletter']['success_action']) ? stripcslashes($data_instance['args']['newsletter']['success_action']) : 'message';
     $success_mesage = isset($data_instance['args']['newsletter']['success_message']) ? stripcslashes($data_instance['args']['newsletter']['success_message']) : __('Welcome to the community!', $_POST['text_domain']);
     $success_url = isset($data_instance['args']['newsletter']['success_url']) ? stripcslashes($data_instance['args']['newsletter']['success_url']) : '';
     // No Email
     if (!isset($_POST['email']) || $_POST['email'] == '') {
         echo json_encode(array('id' => $_POST['data_id'], 'status' => 'warning', 'message' => __('No Email address provided.', $_POST['text_domain'])));
         die;
     }
     // Invalid Email Address
     if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
         echo json_encode(array('id' => $_POST['data_id'], 'status' => 'warning', 'message' => __('Invalid Email provided.', $_POST['text_domain'])));
         die;
     }
     // WordPress
     if ($_POST['type'] == 'wordpress') {
         $newsletter_db = new NNR_Newsletter_Integrations_Submission_v1($_POST['news_table_name']);
         $result = $newsletter_db->add_data(array('data_id' => $_POST['data_id'], 'email' => $_POST['email'], 'first_name' => $_POST['first_name'], 'last_name' => $_POST['last_name']));
         if ($result) {
             echo json_encode(array('id' => $_POST['data_id'], 'status' => 'check', 'success_action' => $success_action, 'url' => $success_url, 'message' => $success_mesage, 'conversion' => apply_filters('nnr_news_int_submission_success_v1', array('data_id' => $_POST['data_id'], 'table_name' => $_POST['stats_table_name']))));
             die;
         } else {
             echo json_encode(array('id' => $_POST['data_id'], 'status' => 'check', 'message' => __('We already have your email!', $_POST['text_domain'])));
             die;
         }
     } else {
         if ($_POST['type'] == 'mailchimp') {
             require_once dirname(dirname(__FILE__)) . '/services/mailchimp/MailChimp.php';
             if (!isset($data_instance['args']['newsletter']['mailchimp']['api_key']) || $data_instance['args']['newsletter']['mailchimp']['api_key'] == '') {
                 echo json_encode(array('id' => $_POST['data_id'], 'status' => 'warning', 'message' => __('MailChimp account is not setup properly.', $_POST['text_domain'])));
                 die;
             }
             if (!isset($data_instance['args']['newsletter']['mailchimp']['list']) || $data_instance['args']['newsletter']['mailchimp']['list'] == '') {
                 echo json_encode(array('id' => $_POST['data_id'], 'status' => 'warning', 'message' => __('MailChimp: No list specified.', $_POST['text_domain'])));
                 die;
             }
             if (!isset($data_instance['args']['newsletter']['mailchimp']['optin'])) {
                 $data_instance['args']['newsletter']['mailchimp']['optin'] = true;
             }
             $MailChimp = new NNR_New_Int_MailChimp($data_instance['args']['newsletter']['mailchimp']['api_key']);
             $result = $MailChimp->call('lists/subscribe', array('id' => $data_instance['args']['newsletter']['mailchimp']['list'], 'email' => array('email' => $_POST['email']), 'merge_vars' => array('FNAME' => $_POST['first_name'], 'LNAME' => $_POST['last_name']), 'double_optin' => $data_instance['args']['newsletter']['mailchimp']['optin'], 'update_existing' => false, 'replace_interests' => false, 'send_welcome' => true));
             if ($result) {
                 if (isset($result['email'])) {
                     echo json_encode(array('id' => $_POST['data_id'], 'status' => 'check', 'success_action' => $success_action, 'url' => $success_url, 'message' => $success_mesage, 'conversion' => apply_filters('nnr_news_int_submission_success_v1', array('data_id' => $_POST['data_id'], 'table_name' => $_POST['stats_table_name']))));
                     die;
                 } else {
                     if (isset($result['status']) && $result['status'] == 'error') {
                         echo json_encode(array('id' => $_POST['data_id'], 'status' => 'warning', 'message' => $result['error']));
                         die;
                     }
                 }
             } else {
                 echo json_encode(array('id' => $_POST['data_id'], 'status' => 'warning', 'message' => __('Unable to subscribe.', $_POST['text_domain'])));
                 die;
             }
         } else {
             if ($_POST['type'] == 'aweber') {
                 require_once dirname(dirname(__FILE__)) . '/services/aweber/aweber_api.php';
                 $aweber = new AWeberAPI($data_instance['args']['newsletter']['aweber']['consumer_key'], $data_instance['args']['newsletter']['aweber']['consumer_secret']);
                 try {
                     $account = $aweber->getAccount($data_instance['args']['newsletter']['aweber']['access_key'], $data_instance['args']['newsletter']['aweber']['access_secret']);
                     $list = $account->loadFromUrl('/accounts/' . $account->id . '/lists/' . $data_instance['args']['newsletter']['aweber']['list_id']);
                     $subscriber = array('email' => $_POST['email'], 'name' => $_POST['first_name'] . ' ' . $_POST['last_name'], 'ip' => $_SERVER['REMOTE_ADDR']);
                     $newSubscriber = $list->subscribers->create($subscriber);
                     echo json_encode(array('id' => $_POST['data_id'], 'status' => 'check', 'success_action' => $success_action, 'url' => $success_url, 'message' => $success_mesage, 'conversion' => apply_filters('nnr_news_int_submission_success_v1', array('data_id' => $_POST['data_id'], 'table_name' => $_POST['stats_table_name']))));
                     die;
                 } catch (AWeberAPIException $exc) {
                     echo json_encode(array('id' => $_POST['data_id'], 'status' => 'warning', 'message' => $exc->message));
                     die;
                 }
             } else {
                 if ($_POST['type'] == 'getresponse') {
                     require_once dirname(dirname(__FILE__)) . '/services/getresponse/jsonRPCClient.php';
                     $api = new jsonRPCClient('http://api2.getresponse.com');
                     try {
                         $api->add_contact($data_instance['args']['newsletter']['getresponse']['api_key'], array('campaign' => $data_instance['args']['newsletter']['getresponse']['campaign'], 'name' => $_POST['first_name'] . ' ' . $_POST['last_name'], 'email' => $_POST['email']));
                         echo json_encode(array('id' => $_POST['data_id'], 'status' => 'check', 'success_action' => $success_action, 'url' => $success_url, 'message' => $success_mesage, 'conversion' => apply_filters('nnr_news_int_submission_success_v1', array('data_id' => $_POST['data_id'], 'table_name' => $_POST['stats_table_name']))));
                         die;
                     } catch (RuntimeException $exc) {
                         $msg = $exc->getMessage();
                         $msg = substr($msg, 0, strpos($msg, ";"));
                         echo json_encode(array('id' => $_POST['data_id'], 'status' => 'warning', 'message' => $msg));
                         die;
                     }
                 } else {
                     if ($_POST['type'] == 'campaignmonitor') {
                         require_once dirname(dirname(__FILE__)) . '/services/campaignmonitor/csrest_subscribers.php';
                         $wrap = new CS_REST_Subscribers($data_instance['args']['newsletter']['campaignmonitor']['list'], $data_instance['args']['newsletter']['campaignmonitor']['api_key']);
                         // Check if subscriber is already subscribed
                         $result = $wrap->get($_POST['email']);
                         if ($result->was_successful()) {
                             echo json_encode(array('id' => $_POST['data_id'], 'status' => 'warning', 'message' => __('You are already subscribed to this list.', $_POST['text_domain'])));
                             die;
                         }
                         $result = $wrap->add(array('EmailAddress' => $_POST['email'], 'Name' => $_POST['first_name'] . ' ' . $_POST['last_name'], 'Resubscribe' => true));
                         if ($result->was_successful()) {
                             echo json_encode(array('id' => $_POST['data_id'], 'status' => 'check', 'success_action' => $success_action, 'url' => $success_url, 'message' => $success_mesage, 'conversion' => apply_filters('nnr_news_int_submission_success_v1', array('data_id' => $_POST['data_id'], 'table_name' => $_POST['stats_table_name']))));
                             die;
                         } else {
                             echo json_encode(array('id' => $_POST['data_id'], 'status' => 'warning', 'message' => $result->response->Message));
                             die;
                         }
                     } else {
                         if ($_POST['type'] == 'madmimi') {
                             require_once dirname(dirname(__FILE__)) . '/services/madmimi/MadMimi.class.php';
                             $mailer = new MadMimi($data_instance['args']['newsletter']['madmimi']['username'], $data_instance['args']['newsletter']['madmimi']['api_key']);
                             try {
                                 // Check if user is already in list
                                 $result = $mailer->Memberships($_POST['email']);
                                 $lists = new SimpleXMLElement($result);
                                 if ($lists->list) {
                                     foreach ($lists->list as $l) {
                                         if ($l->attributes()->{'name'}->{0} == $data_instance['args']['newsletter']['madmimi']['list']) {
                                             echo json_encode(array('id' => $_POST['data_id'], 'status' => 'check', 'message' => __('You are already subscribed to this list.', $_POST['text_domain'])));
                                             die;
                                         }
                                     }
                                 }
                                 $result = $mailer->AddMembership($data_instance['args']['newsletter']['madmimi']['list'], $_POST['email'], array('first_name' => $_POST['first_name'], 'last_name' => $_POST['last_name']));
                                 echo json_encode(array('id' => $_POST['data_id'], 'status' => 'check', 'success_action' => $success_action, 'url' => $success_url, 'message' => $success_mesage, 'conversion' => apply_filters('nnr_news_int_submission_success_v1', array('data_id' => $_POST['data_id'], 'table_name' => $_POST['stats_table_name']))));
                                 die;
                             } catch (RuntimeException $exc) {
                                 echo json_encode(array('id' => $_POST['data_id'], 'status' => 'warning', 'message' => $msg));
                                 die;
                             }
                         } else {
                             if ($_POST['type'] == 'infusionsoft') {
                                 require_once dirname(dirname(__FILE__)) . '/services/infusionsoft/isdk.php';
                                 try {
                                     $infusion_app = new iSDK();
                                     $infusion_app->cfgCon($data_instance['args']['newsletter']['infusionsoft']['app_id'], $data_instance['args']['newsletter']['infusionsoft']['api_key'], 'throw');
                                 } catch (iSDKException $e) {
                                     echo json_encode(array('id' => $_POST['data_id'], 'status' => 'warning', 'message' => $e->getMessage()));
                                     die;
                                 }
                                 if (empty($error_message)) {
                                     $contact_data = $infusion_app->dsQuery('Contact', 1, 0, array('Email' => $_POST['email']), array('Id', 'Groups'));
                                     // Check if contact already exists
                                     if (0 < count($contact_data)) {
                                         if (false === strpos($contact_data[0]['Groups'], $data_instance['args']['newsletter']['infusionsoft']['list'])) {
                                             $infusion_app->grpAssign($contact_data[0]['Id'], $data_instance['args']['newsletter']['infusionsoft']['list']);
                                             echo json_encode(array('id' => $_POST['data_id'], 'status' => 'check', 'success_action' => $success_action, 'url' => $success_url, 'message' => $success_mesage, 'conversion' => apply_filters('nnr_news_int_submission_success_v1', array('data_id' => $_POST['data_id'], 'table_name' => $_POST['stats_table_name']))));
                                             die;
                                         } else {
                                             echo json_encode(array('id' => $_POST['data_id'], 'status' => 'check', 'message' => __('You are already subscribed to this list.', $_POST['text_domain'])));
                                             die;
                                         }
                                     } else {
                                         $new_contact_id = $infusion_app->dsAdd('Contact', array('FirstName' => $_POST['first_name'], 'LastName' => $_POST['last_name'], 'Email' => $_POST['email']));
                                         $infusion_app->grpAssign($new_contact_id, $data_instance['args']['newsletter']['infusionsoft']['list']);
                                         echo json_encode(array('id' => $_POST['data_id'], 'status' => 'check', 'success_action' => $success_action, 'url' => $success_url, 'message' => $success_mesage, 'conversion' => apply_filters('nnr_news_int_submission_success_v1', array('data_id' => $_POST['data_id'], 'table_name' => $_POST['stats_table_name']))));
                                         die;
                                     }
                                 }
                             } else {
                                 if ($_POST['type'] == 'mymail') {
                                     // Check if plugin is activated
                                     if (!function_exists('mymail')) {
                                         echo json_encode(array('id' => $_POST['data_id'], 'status' => 'warning', 'message' => __('MyMail is not activated.', $_POST['text_domain'])));
                                         die;
                                     }
                                     // Add subscriber
                                     $subscriber_id = mymail('subscribers')->add(array('email' => $_POST['email'], 'firstname' => $_POST['first_name'], 'lastname' => $_POST['last_name']), false);
                                     // Add to List
                                     if (!is_wp_error($subscriber_id)) {
                                         mymail('subscribers')->assign_lists($subscriber_id, array($data_instance['args']['newsletter']['mymail']['list']));
                                         echo json_encode(array('id' => $_POST['data_id'], 'status' => 'check', 'success_action' => $success_action, 'url' => $success_url, 'message' => $success_mesage, 'conversion' => apply_filters('nnr_news_int_submission_success_v1', array('data_id' => $_POST['data_id'], 'table_name' => $_POST['stats_table_name']))));
                                         die;
                                     } else {
                                         echo json_encode(array('id' => $_POST['data_id'], 'status' => 'check', 'message' => __('You are already subscribed to this list.', $_POST['text_domain'])));
                                         die;
                                     }
                                 } else {
                                     if ($_POST['type'] == 'activecampaign') {
                                         require_once dirname(dirname(__FILE__)) . '/services/activecampaign/ActiveCampaign.class.php';
                                         $ac = new ActiveCampaign($data_instance['args']['newsletter']['activecampaign']['app_url'], $data_instance['args']['newsletter']['activecampaign']['api_key']);
                                         if (!(int) $ac->credentials_test()) {
                                             echo json_encode(array('id' => $_POST['data_id'], 'status' => 'warning', 'message' => __('Unable to to connect to Active Campaign.', $_POST['text_domain'])));
                                             die;
                                         }
                                         // Add subscriber
                                         $contact_sync = $ac->api("contact/add", array("email" => $_POST['email'], "first_name" => $_POST['first_name'], "last_name" => $_POST['last_name'], "p[" . $data_instance['args']['newsletter']['activecampaign']['list'] . "]" => $data_instance['args']['newsletter']['activecampaign']['list'], "status[" . $data_instance['args']['newsletter']['activecampaign']['list'] . "]" => 1));
                                         if ((int) $contact_sync->success) {
                                             echo json_encode(array('id' => $_POST['data_id'], 'status' => 'check', 'success_action' => $success_action, 'url' => $success_url, 'message' => $success_mesage, 'conversion' => apply_filters('nnr_news_int_submission_success_v1', array('data_id' => $_POST['data_id'], 'table_name' => $_POST['stats_table_name']))));
                                             die;
                                         } else {
                                             echo json_encode(array('id' => $_POST['data_id'], 'status' => 'warning', 'message' => $contact_sync->error));
                                             die;
                                         }
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
     do_action('nnr_news_int_after_submission_add_email_v1');
     echo json_encode(apply_filters('nnr_news_int_submission_add_email_v1', array('id' => $_POST['data_id'], 'status' => 'warning', 'message' => __('Unable to subscribe user. Newsletter not setup properly.', $_POST['text_domain']))));
     die;
     // this is required to terminate immediately and return a proper response
 }
function snp_popup_submit()
{
    global $wpdb;
    $result = array();
    $errors = array();
    $_POST['email'] = trim($_POST['email']);
    if (isset($_POST['name'])) {
        $_POST['name'] = trim($_POST['name']);
    }
    if (!snp_is_valid_email($_POST['email'])) {
        $errors['email'] = 1;
    }
    if (isset($_POST['name']) && !$_POST['name']) {
        $errors['name'] = 1;
    }
    $post_id = intval($_POST['popup_ID']);
    if ($post_id) {
        $POPUP_META = get_post_meta($post_id);
    }
    $cf_data = array();
    if (isset($POPUP_META['snp_cf']) && $post_id) {
        $cf = unserialize($POPUP_META['snp_cf'][0]);
        if (isset($cf) && is_array($cf)) {
            foreach ($cf as $f) {
                if (isset($f['name'])) {
                    if (strpos($f['name'], '[')) {
                        $f['name'] = substr($f['name'], 0, strpos($f['name'], '['));
                    }
                    if (!empty($_POST[$f['name']])) {
                        $cf_data[$f['name']] = $_POST[$f['name']];
                    }
                }
                if (isset($f['required']) && $f['required'] == 'Yes' && !$cf_data[$f['name']]) {
                    $errors[$f['name']] = 1;
                }
            }
        }
    }
    if (count($errors) > 0) {
        $result['Errors'] = $errors;
        $result['Ok'] = false;
    } else {
        $Done = 0;
        if (!empty($_POST['name'])) {
            $names = snp_detect_names($_POST['name']);
        } else {
            $names = array('first' => '', 'last' => '');
        }
        $api_error_msg = '';
        if (snp_get_option('ml_manager') == 'directmail') {
            require_once SNP_DIR_PATH . '/include/directmail/class.directmail.php';
            $form_id = snp_get_option('ml_dm_form_id');
            if ($form_id) {
                $api = new DMSubscribe();
                $retval = $api->submitSubscribeForm($form_id, $_POST['email'], $error_message);
                if ($retval) {
                    $Done = 1;
                } else {
                    // Error... Send by email?
                    $api_error_msg = $error_message;
                }
            }
        } elseif (snp_get_option('ml_manager') == 'sendy') {
            $list_id = $POPUP_META['snp_ml_sendy_list'][0];
            if (!$list_id) {
                $list_id = snp_get_option('ml_sendy_list');
            }
            if ($list_id) {
                $options = array('list' => $list_id, 'boolean' => 'true');
                $args['email'] = $_POST['email'];
                if (!empty($_POST['name'])) {
                    $args['name'] = $_POST['name'];
                }
                if (count($cf_data) > 0) {
                    $args = array_merge($args, (array) $cf_data);
                }
                $content = array_merge($args, $options);
                $postdata = http_build_query($content);
                $ch = curl_init(snp_get_option('ml_sendy_url') . '/subscribe');
                curl_setopt($ch, CURLOPT_HEADER, 0);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_POST, 1);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
                $api_result = curl_exec($ch);
                curl_close($ch);
                if (strval($api_result) == 'true' || strval($api_result) == '1' || strval($api_result) == 'Already subscribed.') {
                    $Done = 1;
                } else {
                    $api_error_msg = $api_result;
                }
            }
        } elseif (snp_get_option('ml_manager') == 'mailchimp') {
            require_once SNP_DIR_PATH . '/include/mailchimp/Mailchimp.php';
            $ml_mc_list = $POPUP_META['snp_ml_mc_list'][0];
            if (!$ml_mc_list) {
                $ml_mc_list = snp_get_option('ml_mc_list');
            }
            if (snp_get_option('ml_mc_apikey') && $ml_mc_list) {
                $api = new Mailchimp(snp_get_option('ml_mc_apikey'));
                $args = array();
                if (!empty($_POST['name'])) {
                    $args = array('FNAME' => $names['first'], 'LNAME' => $names['last']);
                }
                if (count($cf_data) > 0) {
                    $args = array_merge($args, (array) $cf_data);
                }
                try {
                    $double_optin = snp_get_option('ml_mc_double_optin');
                    if ($double_optin == 1) {
                        $double_optin = true;
                    } else {
                        $double_optin = false;
                    }
                    $double_optin = snp_get_option('ml_mc_double_optin');
                    if ($double_optin == 1) {
                        $double_optin = true;
                    } else {
                        $double_optin = false;
                    }
                    $send_welcome = snp_get_option('ml_mc_send_welcome');
                    if ($send_welcome == 1) {
                        $send_welcome = true;
                    } else {
                        $send_welcome = false;
                    }
                    $retval = $api->lists->subscribe($ml_mc_list, array('email' => $_POST['email']), $args, 'html', $double_optin, false, true, $send_welcome);
                    $Done = 1;
                } catch (Exception $e) {
                    if ($e->getCode() == 214) {
                        $Done = 1;
                    } else {
                        $api_error_msg = $e->getMessage();
                    }
                }
            }
        } elseif (snp_get_option('ml_manager') == 'egoi') {
            $ml_egoi_apikey = snp_get_option('ml_egoi_apikey');
            $client = new SoapClient('http://api.e-goi.com/v2/soap.php?wsdl');
            try {
                $ml_egoi_list = $POPUP_META['snp_ml_egoi_list'][0];
                if (!$ml_egoi_list) {
                    $ml_egoi_list = snp_get_option('ml_egoi_list');
                }
                $args = array('apikey' => $ml_egoi_apikey, 'listID' => $ml_egoi_list, 'email' => $_POST['email']);
                if (!empty($_POST['name'])) {
                    $args['first_name'] = $names['first'];
                    $args['last_name'] = $names['last'];
                }
                if (count($cf_data) > 0) {
                    $CustomFields = array();
                    foreach ($cf_data as $k => $v) {
                        $args[$k] = $v;
                    }
                }
                $res = $client->addSubscriber($args);
                if (isset($res['UID'])) {
                    $Done = 1;
                }
            } catch (Exception $e) {
                // Error...
                // We'll send this by email.
            }
        } elseif (snp_get_option('ml_manager') == 'getresponse') {
            $ml_gr_apikey = snp_get_option('ml_gr_apikey');
            require_once SNP_DIR_PATH . '/include/getresponse/jsonRPCClient.php';
            $api = new jsonRPCClient('http://api2.getresponse.com');
            try {
                $ml_gr_list = $POPUP_META['snp_ml_gr_list'][0];
                if (!$ml_gr_list) {
                    $ml_gr_list = snp_get_option('ml_gr_list');
                }
                $args = array('campaign' => $ml_gr_list, 'email' => $_POST['email']);
                if (!empty($_POST['name'])) {
                    $args['name'] = $_POST['name'];
                }
                if (count($cf_data) > 0) {
                    $CustomFields = array();
                    foreach ($cf_data as $k => $v) {
                        $CustomFields[] = array('name' => $k, 'content' => $v);
                    }
                    $args['customs'] = $CustomFields;
                }
                $res = $api->add_contact($ml_gr_apikey, $args);
                $Done = 1;
            } catch (Exception $e) {
                // Error...
                // We'll send this by email.
                $api_error_msg = $e->getMessage();
            }
        } elseif (snp_get_option('ml_manager') == 'campaignmonitor') {
            require_once SNP_DIR_PATH . '/include/campaignmonitor/csrest_subscribers.php';
            $ml_cm_list = $POPUP_META['snp_ml_cm_list'][0];
            if (!$ml_cm_list) {
                $ml_cm_list = snp_get_option('ml_cm_list');
            }
            $wrap = new CS_REST_Subscribers($ml_cm_list, snp_get_option('ml_cm_apikey'));
            $args = array('EmailAddress' => $_POST['email'], 'Resubscribe' => true);
            if (!empty($_POST['name'])) {
                $args['Name'] = $_POST['name'];
            }
            if (count($cf_data) > 0) {
                $CustomFields = array();
                foreach ($cf_data as $k => $v) {
                    $CustomFields[] = array('Key' => $k, 'Value' => $v);
                }
                $args['CustomFields'] = $CustomFields;
            }
            $res = $wrap->add($args);
            if ($res->was_successful()) {
                $Done = 1;
            } else {
                // Error...
                // We'll send this by email.
                $api_error_msg = 'Failed with code ' . $res->http_status_code;
            }
        } elseif (snp_get_option('ml_manager') == 'icontact') {
            require_once SNP_DIR_PATH . '/include/icontact/iContactApi.php';
            iContactApi::getInstance()->setConfig(array('appId' => snp_get_option('ml_ic_addid'), 'apiPassword' => snp_get_option('ml_ic_apppass'), 'apiUsername' => snp_get_option('ml_ic_username')));
            $oiContact = iContactApi::getInstance();
            $res1 = $oiContact->addContact($_POST['email'], null, null, isset($names['first']) ? $names['first'] : '', isset($names['last']) ? $names['last'] : '', null, null, null, null, null, null, null, null, null);
            if ($res1->contactId) {
                $ml_ic_list = $POPUP_META['snp_ml_ic_list'][0];
                if (!$ml_ic_list) {
                    $ml_ic_list = snp_get_option('ml_ic_list');
                }
                if ($oiContact->subscribeContactToList($res1->contactId, $ml_ic_list, 'normal')) {
                    $Done = 1;
                }
            } else {
                // Error...
                // We'll send this by email.
                $api_error_msg = 'iContact Problem!';
            }
        } elseif (snp_get_option('ml_manager') == 'constantcontact') {
            require_once SNP_DIR_PATH . '/include/constantcontact/class.cc.php';
            $cc = new cc(snp_get_option('ml_cc_username'), snp_get_option('ml_cc_pass'));
            $send_welcome = snp_get_option('ml_cc_send_welcome');
            if ($send_welcome == 1) {
                $cc->set_action_type('contact');
            }
            $email = $_POST['email'];
            $contact_list = $POPUP_META['snp_ml_cc_list'][0];
            if (!$contact_list) {
                $contact_list = snp_get_option('ml_cc_list');
            }
            $extra_fields = array();
            if (!empty($names['first'])) {
                $extra_fields['FirstName'] = $names['first'];
            }
            if (!empty($names['last'])) {
                $extra_fields['LastName'] = $names['last'];
            }
            if (count($cf_data) > 0) {
                $extra_fields = array_merge($extra_fields, (array) $cf_data);
            }
            $contact = $cc->query_contacts($email);
            if ($contact) {
                $status = $cc->update_contact($contact['id'], $email, $contact_list, $extra_fields);
                if ($status) {
                    $Done = 1;
                } else {
                    $api_error_msg = "Contact Operation failed: " . $cc->http_get_response_code_error($cc->http_response_code);
                }
            } else {
                $new_id = $cc->create_contact($email, $contact_list, $extra_fields);
                if ($new_id) {
                    $Done = 1;
                } else {
                    $api_error_msg = "Contact Operation failed: " . $cc->http_get_response_code_error($cc->http_response_code);
                }
            }
        } elseif (snp_get_option('ml_manager') == 'madmimi') {
            require_once SNP_DIR_PATH . '/include/madmimi/MadMimi.class.php';
            if (snp_get_option('ml_madm_username') && snp_get_option('ml_madm_apikey')) {
                $mailer = new MadMimi(snp_get_option('ml_madm_username'), snp_get_option('ml_madm_apikey'));
                $user = array('email' => $_POST['email']);
                if (!empty($names['first'])) {
                    $user['FirstName'] = $names['first'];
                }
                if (!empty($names['last'])) {
                    $user['LastName'] = $names['last'];
                }
                if (count($cf_data) > 0) {
                    $user = array_merge($user, (array) $cf_data);
                }
                $ml_madm_list = $POPUP_META['snp_ml_madm_list'][0];
                if (!$ml_madm_list) {
                    $ml_madm_list = snp_get_option('ml_madm_list');
                }
                $user['add_list'] = $ml_madm_list;
                $res = $mailer->AddUser($user);
                $Done = 1;
            }
        } elseif (snp_get_option('ml_manager') == 'infusionsoft') {
            require_once SNP_DIR_PATH . '/include/infusionsoft/infusionsoft.php';
            if (snp_get_option('ml_inf_subdomain') && snp_get_option('ml_inf_apikey')) {
                $infusionsoft = new Infusionsoft(snp_get_option('ml_inf_subdomain'), snp_get_option('ml_inf_apikey'));
                $user = array('Email' => $_POST['email']);
                if (!empty($names['first'])) {
                    $user['FirstName'] = $names['first'];
                }
                if (!empty($names['last'])) {
                    $user['LastName'] = $names['last'];
                }
                if (count($cf_data) > 0) {
                    $user = array_merge($user, (array) $cf_data);
                }
                $ml_inf_list = $POPUP_META['snp_ml_inf_list'][0];
                if (!$ml_inf_list) {
                    $ml_inf_list = snp_get_option('ml_inf_list');
                }
                $contact_id = $infusionsoft->contact('add', $user);
                $r = $infusionsoft->APIEmail('optIn', $_POST['email'], "Ninja Popups on " . get_bloginfo());
                if ($contact_id && $ml_inf_list) {
                    $infusionsoft->contact('addToGroup', $contact_id, $ml_inf_list);
                }
                if ($contact_id) {
                    $Done = 1;
                }
            }
        } elseif (snp_get_option('ml_manager') == 'aweber') {
            require_once SNP_DIR_PATH . '/include/aweber/aweber_api.php';
            if (get_option('snp_ml_aw_auth_info')) {
                $aw = get_option('snp_ml_aw_auth_info');
                try {
                    $aweber = new AWeberAPI($aw['consumer_key'], $aw['consumer_secret']);
                    $account = $aweber->getAccount($aw['access_key'], $aw['access_secret']);
                    $aw_list = $POPUP_META['snp_ml_aw_lists'][0];
                    if (!$aw_list) {
                        $aw_list = snp_get_option('ml_aw_lists');
                    }
                    $list = $account->loadFromUrl('/accounts/' . $account->id . '/lists/' . $aw_list);
                    $subscriber = array('email' => $_POST['email'], 'ip' => $_SERVER['REMOTE_ADDR']);
                    if (!empty($_POST['name'])) {
                        $subscriber['name'] = $_POST['name'];
                    }
                    if (count($cf_data) > 0) {
                        $subscriber['custom_fields'] = $cf_data;
                    }
                    $r = $list->subscribers->create($subscriber);
                    $Done = 1;
                } catch (AWeberException $e) {
                    $api_error_msg = $e->getMessage();
                }
            }
        } elseif (snp_get_option('ml_manager') == 'wysija' && class_exists('WYSIJA')) {
            $ml_wy_list = $POPUP_META['snp_ml_wy_list'][0];
            if (!$ml_wy_list) {
                $ml_wy_list = snp_get_option('ml_wy_list');
            }
            $userData = array('email' => $_POST['email'], 'firstname' => $names['first'], 'lastname' => $names['last']);
            $data = array('user' => $userData, 'user_list' => array('list_ids' => array($ml_wy_list)));
            $userHelper =& WYSIJA::get('user', 'helper');
            if ($userHelper->addSubscriber($data)) {
                $Done = 1;
            } else {
                $api_error_msg = 'MailPoet Problem!';
            }
        } elseif (snp_get_option('ml_manager') == 'sendpress') {
            $ml_sp_list = $POPUP_META['snp_ml_sp_list'][0];
            if (!$ml_sp_list) {
                $ml_sp_list = snp_get_option('ml_sp_list');
            }
            try {
                SendPress_Data::subscribe_user($ml_sp_list, $_POST['email'], $names['first'], $names['last'], 2);
                $Done = 1;
            } catch (Exception $e) {
                $api_error_msg = 'SendPress Problem!';
            }
        } elseif (snp_get_option('ml_manager') == 'mymail') {
            $userdata = array('firstname' => $names['first'], 'lastname' => $names['last']);
            $ml_mm_list = $POPUP_META['snp_ml_mm_list'][0];
            if (!$ml_mm_list) {
                $ml_mm_list = snp_get_option('ml_mm_list');
            }
            $lists = array($ml_mm_list);
            if (function_exists('mymail')) {
                $entry = $userdata;
                $entry['email'] = $_POST['email'];
                $double_optin = snp_get_option('ml_mm_double_optin');
                if ($double_optin == 1) {
                    $entry['status'] = 0;
                } else {
                    $entry['status'] = 1;
                }
                if (count($cf_data) > 0) {
                    foreach ($cf_data as $k => $v) {
                        $entry[$k] = $v;
                    }
                }
                $subscriber_id = mymail('subscribers')->add($entry, true);
                if (!is_wp_error($subscriber_id)) {
                    $success = mymail('subscribers')->assign_lists($subscriber_id, $lists, false);
                }
                if ($success) {
                    $Done = 1;
                } else {
                    $api_error_msg = 'MyMail Problem!';
                }
            } else {
                $return = mymail_subscribe($_POST['email'], $userdata, $lists);
                if (!is_wp_error($return)) {
                    $Done = 1;
                } else {
                    $api_error_msg = 'MyMail Problem!';
                }
            }
        } elseif (snp_get_option('ml_manager') == 'csv' && snp_get_option('ml_csv_file') && is_writable(SNP_DIR_PATH . 'csv/')) {
            if (!isset($_POST['name'])) {
                $_POST['name'] = '';
            }
            if (count($cf_data) > 0) {
                $CustomFields = '';
                foreach ($cf_data as $k => $v) {
                    $CustomFields .= $k . ' = ' . $v . ';';
                }
            }
            $data = $_POST['email'] . ";" . $_POST['name'] . ";" . $CustomFields . get_the_title($_POST['popup_ID']) . " (" . $_POST['popup_ID'] . ");" . date('Y-m-d H:i') . ";" . $_SERVER['REMOTE_ADDR'] . ";\n";
            if (file_put_contents(SNP_DIR_PATH . 'csv/' . snp_get_option('ml_csv_file'), $data, FILE_APPEND | LOCK_EX) !== FALSE) {
                $Done = 1;
            } else {
                $api_error_msg = 'CSV Problem!';
            }
        }
        if (snp_get_option('ml_manager') == 'email' || !$Done) {
            $Email = snp_get_option('ml_email');
            if (!$Email) {
                $Email = get_bloginfo('admin_email');
            }
            if (!isset($_POST['name'])) {
                $_POST['name'] = '--';
            }
            $error_mgs = '';
            if ($api_error_msg != '') {
                $error_mgs .= "IMPORTANT! You have received this message because connection to your e-mail marketing software failed. Please check connection setting in the plugin configuration.\n";
                $error_mgs .= $api_error_msg . "\n";
            }
            $cf_msg = '';
            if (count($cf_data) > 0) {
                foreach ($cf_data as $k => $v) {
                    $cf_msg .= $k . ": " . $v . "\n";
                }
            }
            $msg = "New subscription on " . get_bloginfo() . "\n" . $error_mgs . "\n" . "E-mail: " . $_POST['email'] . "\n" . "Name: " . $_POST['name'] . "\n" . $cf_msg . "\n" . "Form: " . get_the_title($_POST['popup_ID']) . " (" . $_POST['popup_ID'] . ")\n" . "\n" . "Date: " . date('Y-m-d H:i') . "\n" . "IP: " . $_SERVER['REMOTE_ADDR'] . "";
            wp_mail($Email, "New subscription on " . get_bloginfo(), $msg);
        }
        $result['Ok'] = true;
    }
    echo json_encode($result);
    die('');
}
function seed_cspv4_emaillist_campaignmonitor_add_subscriber($args)
{
    global $seed_cspv4, $seed_cspv4_post_result;
    extract($seed_cspv4);
    require_once SEED_CSPV4_PLUGIN_PATH . 'lib/nameparse.php';
    if (class_exists('CS_REST_Subscribers')) {
        //trigger_error("Duplicate: Another Campaign Moniter client library is already in scope.", E_USER_WARNING);
    } else {
        require_once SEED_CSPV4_PLUGIN_PATH . 'extentions/campaignmonitor/campaign_monitor/csrest_subscribers.php';
    }
    // If tracking enabled
    if (!empty($enable_reflink)) {
        seed_cspv4_emaillist_database_add_subscriber();
    }
    $apikey = $campaignmonitor_api_key;
    $listid = $campaignmonitor_listid;
    $name = '';
    if (!empty($_REQUEST['name'])) {
        $name = $_REQUEST['name'];
    }
    $email = $_REQUEST['email'];
    $fname = '';
    $lname = '';
    if (!empty($name)) {
        $name = seed_cspv4_parse_name($name);
        $fname = $name['first'];
        $lname = $name['last'];
    }
    $api = new CS_REST_Subscribers($listid, $apikey);
    $response = $api->add(array('EmailAddress' => $email, 'Name' => $fname . ' ' . $lname, 'Resubscribe' => true));
    //var_dump($name);
    //var_dump($response);
    if ($response->was_successful()) {
        if (empty($seed_cspv4_post_result['status'])) {
            $seed_cspv4_post_result['status'] = '200';
        }
    } else {
        $seed_cspv4_post_result['status'] = '500';
        $seed_cspv4_post_result['status'] = $txt_api_error_msg;
        $seed_cspv4_post_result['status'] = 'alert-danger';
    }
}
<?php

require_once 'csrest_clients.php';
require_once 'csrest_general.php';
require_once 'csrest_subscribers.php';
$auth = array('api_key' => $options_array['campaign_monitor']['api_key']);
$wrap = new CS_REST_Subscribers($campaign_monitor_list, $auth);
$result = $wrap->add(array('EmailAddress' => $email, 'Name' => $fname . ' ' . $lname, 'CustomFields' => array(), 'Resubscribe' => true));