/**
  * 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));
 }
Example #2
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 massUnsubscribeAction()
 {
     $session = Mage::getSingleton('core/session');
     Mage::helper('campaignmonitor')->log("massUnsubscribeAction");
     $subscribersIds = $this->getRequest()->getParam('subscriber');
     if (!is_array($subscribersIds)) {
         Mage::getSingleton('adminhtml/session')->addError(Mage::helper('newsletter')->__('Please select subscriber(s)'));
         $this->_redirect('*/*/index');
     } else {
         try {
             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();
             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();
             }
             foreach ($subscribersIds as $subscriberId) {
                 $subscriber = Mage::getModel('newsletter/subscriber')->load($subscriberId);
                 $email = $subscriber->getEmail();
                 Mage::helper('campaignmonitor')->log($this->__("Unsubscribing: %s", $email));
                 try {
                     $result = $client->unsubscribe($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
                         $client->unsubscribe($email);
                     }
                 } catch (Exception $e) {
                     Mage::helper('campaignmonitor')->log("Error in CampaignMonitor SOAP call: " . $e->getMessage());
                 }
             }
         } catch (Exception $e) {
             Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
         }
     }
     parent::massUnsubscribeAction();
 }
 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 function email_list_remove($uid = NULL)
 {
     $wrap = new CS_REST_Subscribers(CM_MEMBERLIST, CM_APIKEY);
     error_log("email list uid = " . $uid, 0);
     // future (if grind supports multiple emails per person you will need
     // to ensure this is a primary email that you are adding
     // if we are passing in a userid init their email address and unsub that.
     // otherwise assume we have an email
     if (isset($uid)) {
         $this->email = $this->init($uid);
         error_log("This->email:" . serialize($this->email));
     } else {
         if (!isset($this->email->address)) {
             // bail we have no email address
             return false;
             exit;
         }
     }
     $result = $wrap->delete($this->email->address);
     if ($result->was_successful()) {
         error_log("Subscribed with code " . $result->http_status_code, 0);
     } else {
         error_log('Failed with code ' . $result->http_status_code . "\n<br /><pre>", 0);
     }
 }
 /**
  * Subscribe
  *
  * @see  https://github.com/campaignmonitor/createsend-php
  * @see  http://www.campaignmonitor.com/api/
  * @param  string                 $apiKey
  * @param  string                 $listId
  * @param  array                  $subscribers
  * @return CS_REST_Wrapper_Result
  */
 protected function subscribe($apiKey, $listId, $subscribers)
 {
     $auth = array('api_key' => $apiKey);
     $wrap = new \CS_REST_Subscribers($listId, $auth);
     $result = $wrap->import($subscribers, true);
     return $result;
 }
Example #10
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);
 }
Example #11
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>';
}
Example #12
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>" }';
    }
}
 public function indexAction()
 {
     $session = Mage::getSingleton('core/session');
     // Don't do anything if we didn't get the email parameter
     if (isset($_GET['email'])) {
         $email = $_GET['email'];
         // Get the CampaignMonitor credentials
         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 that the email address actually is unsubscribed in Campaign Monitor.
         if ($auth && $listID) {
             // Retrieve the subscriber
             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(sprintf("Error in SOAP call: %s", $e->getMessage()));
                 $session->addException($e, $this->__('There was a problem with the unsubscription'));
                 $this->_redirectReferer();
             }
             // Get the subscription state
             $state = "";
             try {
                 if ($result->was_successful() && isset($result->response->State)) {
                     $state = $result->response->State;
                 }
             } catch (Exception $e) {
                 Mage::helper('campaignmonitor')->log(sprintf("Error in SOAP call: %s", $e->getMessage()));
                 $session->addException($e, $this->__('There was a problem with the unsubscription'));
                 $this->_redirectReferer();
             }
             // If we are unsubscribed, deleted or not subscribed in Campaign Monitor, mark us as
             // unsubscribed in Magento.
             if ($state != "Unsubscribed" && $state != "Not Subscribed" && $state != "Deleted") {
                 try {
                     $result = $client->unsubscribe($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->unsubscribe($email);
                     }
                     if ($result->was_successful()) {
                         Mage::getModel('newsletter/subscriber')->loadByEmail($email)->unsubscribe();
                         Mage::getSingleton('customer/session')->addSuccess($this->__('You were successfully unsubscribed'));
                     }
                 } catch (Exception $e) {
                     Mage::helper('campaignmonitor')->log(sprintf("%s", $e->getMessage()));
                     Mage::getSingleton('customer/session')->addError($this->__('There was an error while saving your subscription details'));
                 }
             } elseif ($state == "Unsubscribed" || $state == "Not Subscribed" || $state == "Deleted") {
                 try {
                     $subscriberStatus = Mage::getModel('newsletter/subscriber')->loadByEmail($email)->getStatus();
                     // 2 = Not Activated
                     // 1 = Subscribed
                     // 3 = Unsubscribed
                     // 4 = Unconfirmed
                     if ($subscriberStatus != 3) {
                         Mage::getModel('newsletter/subscriber')->loadByEmail($email)->unsubscribe();
                         Mage::getSingleton('customer/session')->addSuccess($this->__('You were successfully unsubscribed'));
                         $block = Mage::getModel('cms/block')->load('unsubscribe-custom-message');
                         if ($block) {
                             Mage::getSingleton('customer/session')->addNotice($block->getContent());
                         }
                     } else {
                         Mage::getSingleton('customer/session')->addSuccess($this->__('You have already unsubscribed to our newsletter, click <a href="/subscribe">here</a> to resubscribe'));
                     }
                 } catch (Exception $e) {
                     Mage::helper('campaignmonitor')->log(sprintf("%s", $e->getMessage()));
                     Mage::getSingleton('customer/session')->addError($this->__('There was an error while saving your subscription details'));
                 }
             } else {
                 Mage::helper('campaignmonitor')->log($this->__("Not unsubscribing %s, not unsubscribed in Campaign Monitor", $email));
             }
         }
     }
     $this->_redirect('/');
 }
Example #14
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);
 }
Example #15
0
<?php

require_once '../../csrest_subscribers.php';
$wrap = new CS_REST_Subscribers('Your list ID', 'Your API Key');
$result = $wrap->import(array(array('EmailAddress' => 'Subscriber email', 'Name' => 'Subscriber name', 'CustomFields' => array(array('Key' => 'Field Key', 'Value' => 'Field Value'))), array('EmailAddress' => '2nd Subscriber email', 'Name' => '2nd Subscriber name', 'CustomFields' => array(array('Key' => 'Field Key', 'Value' => 'Field Value')))), true);
echo "Result of POST /api/v3/subscribers/{list id}/import.{format}\n<br />";
if ($result->was_successful()) {
    echo "Subscribed with results <pre>";
    var_dump($result->response);
} else {
    echo 'Failed with code ' . $result->http_status_code . "\n<br /><pre>";
    var_dump($result->response);
    echo '</pre>';
    if ($result->response->ResultData->TotalExistingSubscribers > 0) {
        echo 'Updated ' . $result->response->ResultData->TotalExistingSubscribers . ' existing subscribers in the list';
    } else {
        if ($result->response->ResultData->TotalNewSubscribers > 0) {
            echo 'Added ' . $result->response->ResultData->TotalNewSubscribers . ' to the list';
        } else {
            if (count($result->response->ResultData->DuplicateEmailsInSubmission) > 0) {
                echo $result->response->ResultData->DuplicateEmailsInSubmission . ' were duplicated in the provided array.';
            }
        }
    }
    echo 'The following emails failed to import correctly.<pre>';
    var_dump($result->response->ResultData->FailureDetails);
}
echo '</pre>';
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('');
}
Example #17
0
            $use_email = $toll_email;
            $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'];
Example #18
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();
	}
Example #19
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);
 }
<?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->get_history('Email address');
echo "Result of GET /api/v3.1/subscribers/{list id}/history.{format}?email={email}\n<br />";
if ($result->was_successful()) {
    echo "Got subscriber history <pre>";
    var_dump($result->response);
} else {
    echo '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();
 }
 public static function cmdr_mass_update()
 {
     global $cmdr_fields_to_hide;
     $cmdr_user_fields = (array) unserialize(base64_decode(get_option('cmdr_user_fields')));
     if (!class_exists('CS_REST_Lists')) {
         require_once CMDR_PLUGIN_PATH . 'campaignmonitor-createsend-php/csrest_lists.php';
     }
     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_l = new CS_REST_Lists(get_option('cmdr_list_id'), $auth);
     $wrap_s = new CS_REST_Subscribers(get_option('cmdr_list_id'), $auth);
     // Update custom fields
     $missing_fields = $cmdr_user_fields;
     $result = $wrap_l->get_custom_fields();
     if (!$result->was_successful()) {
         self::$error = $result->response;
         return false;
     }
     if (is_array($result->response)) {
         foreach ($result->response as $key => $field) {
             $k = str_replace('[', '', str_replace(']', '', $field->Key));
             if (in_array($k, $missing_fields)) {
                 unset($missing_fields[array_search($k, $missing_fields)]);
             }
         }
     }
     foreach ($missing_fields as $key => $field) {
         if (!in_array($field, $cmdr_fields_to_hide)) {
             $result = $wrap_l->create_custom_field(array('FieldName' => $field, 'Key' => $field, 'DataType' => CS_REST_CUSTOM_FIELD_TYPE_TEXT));
             if (!$result->was_successful()) {
                 self::$error = $result->response;
                 return false;
             }
         }
     }
     // Update users
     $missing_users = array();
     $u = get_users();
     foreach ($u as $key => $value) {
         $missing_users[] = $value->user_email;
     }
     $result = $wrap_l->get_active_subscribers('', 1, 1000);
     if (!$result->was_successful()) {
         self::$error = $result->response;
         return false;
     }
     $i = 2;
     while (count($result->response->Results)) {
         if (!empty($result->response->Results) && is_array($result->response->Results)) {
             foreach ($result->response->Results as $key => $subscriber) {
                 set_time_limit(60);
                 $user = get_user_by('email', $subscriber->EmailAddress);
                 if ($user) {
                     $args = array();
                     if (trim($user->first_name . ' ' . $user->last_name) != trim($subscriber->Name)) {
                         $args['Name'] = $user->first_name . ' ' . $user->last_name;
                     }
                     $custom_values = array();
                     foreach ($subscriber->CustomFields as $field) {
                         $k = str_replace('[', '', str_replace(']', '', $field->Key));
                         $custom_values[$k] = $field->Value;
                     }
                     foreach ($cmdr_user_fields as $key => $field) {
                         if (!in_array($field, $cmdr_fields_to_hide)) {
                             if (empty($custom_values[$field]) || trim($custom_values[$field]) != trim(get_user_meta($user->ID, $field, true))) {
                                 // We export scalar values only
                                 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 (count($args)) {
                         $result_tmp = $wrap_s->update($user->user_email, $args);
                         if (!$result_tmp->was_successful()) {
                             self::$error = $result_tmp->response;
                             return false;
                         }
                     }
                 }
                 if (in_array($subscriber->EmailAddress, $missing_users)) {
                     unset($missing_users[array_search($subscriber->EmailAddress, $missing_users)]);
                 }
             }
         }
         $result = $wrap_l->get_active_subscribers('', $i, 1000);
         if (!$result->was_successful()) {
             self::$error = $result->response;
             return false;
         }
         $i++;
     }
     // Get bounced and unsubscribed users
     $unsubscribed = array();
     $result = $wrap_l->get_unsubscribed_subscribers('', 1, 1000);
     if (!$result->was_successful()) {
         self::$error = $result->response;
         return false;
     }
     $i = 2;
     while (count($result->response->Results)) {
         foreach ($result->response->Results as $key => $subscriber) {
             $unsubscribed[] = $subscriber->EmailAddress;
         }
         $result = $wrap_l->get_unsubscribed_subscribers('', $i, 1000);
         if (!$result->was_successful()) {
             self::$error = $result->response;
             return false;
         }
         $i++;
     }
     $bounced = array();
     $result = $wrap_l->get_bounced_subscribers('', 1, 1000);
     if (!$result->was_successful()) {
         self::$error = $result->response;
         return false;
     }
     $i = 2;
     while (count($result->response->Results)) {
         foreach ($result->response->Results as $key => $subscriber) {
             $bounced[] = $subscriber->EmailAddress;
         }
         $result = $wrap_l->get_bounced_subscribers('', $i, 1000);
         if (!$result->was_successful()) {
             self::$error = $result->response;
             return false;
         }
         $i++;
     }
     $subscribers = array();
     foreach ($missing_users as $key => $user_email) {
         if (!in_array($user_email, $unsubscribed) && !in_array($user_email, $bounced)) {
             // Subscriber does not exist, let's add him
             $user = get_user_by('email', $user_email);
             if ($user) {
                 $args = array('EmailAddress' => $user->user_email, 'Name' => $user->first_name . ' ' . $user->last_name, 'CustomFields' => array());
                 foreach ($cmdr_user_fields as $key => $field) {
                     if (!in_array($field, $cmdr_fields_to_hide)) {
                         // We export scalar values only
                         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' => '');
                         }
                     }
                 }
                 $subscribers[] = $args;
             }
         }
     }
     while (count($subscribers)) {
         set_time_limit(60);
         $subscribers1000 = array();
         for ($i = 0; $i < 1000; $i++) {
             $subscribers1000[] = array_shift($subscribers);
             if (!count($subscribers)) {
                 break;
             }
         }
         $result = $wrap_s->import($subscribers1000, true);
         if (!$result->was_successful()) {
             self::$error = $result->response;
             return false;
         }
     }
     return true;
 }
Example #24
0
<?php

require_once '../../csrest_subscribers.php';
$wrap = new CS_REST_Subscribers('Your list ID', 'Your API Key');
$result = $wrap->delete('Email Address');
echo "Result of DELETE /api/v3/subscribers/{list id}.{format}?email={emailAddress}\n<br />";
if ($result->was_successful()) {
    echo "Unsubscribed with code " . $result->http_status_code;
} else {
    echo 'Failed with code ' . $result->http_status_code . "\n<br /><pre>";
    var_dump($result->response);
    echo '</pre>';
}
Example #25
0
<?php

require_once '../../csrest_subscribers.php';
$wrap = new CS_REST_Subscribers('Your list ID', 'Your API Key');
$result = $wrap->get('Email address');
echo "Result of GET /api/v3/subscribers/{list id}.{format}?email={email}\n<br />";
if ($result->was_successful()) {
    echo "Got subscriber <pre>";
    var_dump($result->response);
} else {
    echo 'Failed with code ' . $result->http_status_code . "\n<br /><pre>";
    var_dump($result->response);
}
echo '</pre>';
<?php

require_once '../../csrest_subscribers.php';
$wrap = new CS_REST_Subscribers('Your list ID', 'Your API Key');
$result = $wrap->unsubscribe('Email Address');
echo "Result of GET /api/v3/subscribers/{list id}/unsubscribe.{format}\n<br />";
if ($result->was_successful()) {
    echo "Unsubscribed with code " . $result->http_status_code;
} else {
    echo 'Failed with code ' . $result->http_status_code . "\n<br /><pre>";
    var_dump($result->response);
    echo '</pre>';
}
Example #27
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>';
}
Example #28
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->import(array(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'))), array('EmailAddress' => '2nd Subscriber email', 'Name' => '2nd 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')))), false);
echo "Result of POST /api/v3.1/subscribers/{list id}/import.{format}\n<br />";
if ($result->was_successful()) {
    echo "Subscribed with results <pre>";
    var_dump($result->response);
} else {
    echo 'Failed with code ' . $result->http_status_code . "\n<br /><pre>";
    var_dump($result->response);
    echo '</pre>';
    if ($result->response->ResultData->TotalExistingSubscribers > 0) {
        echo 'Updated ' . $result->response->ResultData->TotalExistingSubscribers . ' existing subscribers in the list';
    } else {
        if ($result->response->ResultData->TotalNewSubscribers > 0) {
            echo 'Added ' . $result->response->ResultData->TotalNewSubscribers . ' to the list';
        } else {
            if (count($result->response->ResultData->DuplicateEmailsInSubmission) > 0) {
                echo $result->response->ResultData->DuplicateEmailsInSubmission . ' were duplicated in the provided array.';
            }
        }
    }
    echo 'The following emails failed to import correctly.<pre>';
    var_dump($result->response->ResultData->FailureDetails);
}
echo '</pre>';
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';
    }
}
  * If Resubscribe is specified as false, the subscriber will not be re-added to the active list.
  */
 $campaignmonitor_contact['Resubscribe'] = true;
 $campaignmonitor_contact['CustomFields'] = array();
 // FIELDS
 if (!empty($list_v['fields'])) {
     foreach ($list_v['fields'] as $field_v) {
         if ($field_v['list_field_id'] == 'EmailAddress' || $field_v['list_field_id'] == 'Name') {
             // 'Name' IS NOT a mandatory field
             $campaignmonitor_contact[$field_v['list_field_id']] = getElementValue($field_v['element_id']);
         }
         if ($field_v['list_field_id'] != 'EmailAddress' && $field_v['list_field_id'] != 'Name') {
             $campaignmonitor_contact['CustomFields'][] = array('Key' => $field_v['list_field_id'], 'Value' => getElementValue($field_v['element_id']));
         }
     }
     $wrap = new CS_REST_Subscribers($list_id, $campaignmonitor_auth);
     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.