示例#1
0
 public function run($args)
 {
     $subscribers = User::model()->findAllByAttributes(array('newsletter' => true, 'previous_newsletter_state' => false));
     $batch = array();
     foreach ($subscribers as $s) {
         $batch[] = array('EMAIL' => $s->email, 'FNAME' => $s->first_name, 'LNAME' => $s->last_name);
         $s->previous_newsletter_state = true;
         $s->save();
     }
     $api = new MCAPI(Yii::app()->params['mc_apikey']);
     $result = $api->listBatchSubscribe(Yii::app()->params['mc_listID'], $batch, false);
     if (isset($result['errors'])) {
         foreach ($result['errors'] as $e) {
             if ($e['code'] == 212) {
                 //User unsubscribed, need to resubscribe individually
                 $user = User::model()->findByAttributes(array('email' => $e['email']));
                 if ($user !== null) {
                     $info = array('FNAME' => $user->first_name, 'LNAME' => $user->last_name);
                     $api->listSubscribe(Yii::app()->params['mc_listID'], $user->email, $info);
                     if ($api->errorCode) {
                         echo "Subscribe {$user->email} failed!\n";
                         echo "code:" . $api->errorCode . "\n";
                         echo "msg :" . $api->errorMessage . "\n";
                     } else {
                         echo "Re-Subscribe {$user->email} Successfully\n";
                     }
                 }
             } else {
                 if ($e['code'] != 214) {
                     print_r($e);
                 }
             }
         }
     }
     $unsubscribers = User::model()->findAllByAttributes(array('newsletter' => false, 'previous_newsletter_state' => true));
     $batch = array();
     foreach ($unsubscribers as $u) {
         $batch[] = $u->email;
         $u->previous_newsletter_state = $u->newsletter = 0;
         $u->save();
     }
     $result = $api->listBatchUnsubscribe(Yii::app()->params['mc_listID'], $batch);
     if (isset($result['errors'])) {
         foreach ($result['errors'] as $e) {
             if ($e['code'] != 215) {
                 print_r($e);
             }
         }
     }
 }
 /**
  * Runs through all local users for a given list
  *
  * @param string $listId
  */
 protected function processLocalUsers($listId)
 {
     $batch = 0;
     $results = array('successCount' => 0, 'errorCount' => 0, 'errors' => array());
     while ($users = $this->getUsers($listId, $batch++, $this->_batchSize)) {
         $batchResult = $this->_mailChimp->listBatchSubscribe($listId, $users, $this->_mailChimpOptions['doubleOptIn'], true, true);
         if ($this->_mailChimp->errorCode) {
             throw new Galahad_MailChimp_Synchronizer_Exception('Error with batch subscribe: ' . $this->_mailChimp->errorMessage);
         } else {
             $this->_batchLog[] = "Subscribe Batch {$batch}: {$batchResult['success_count']} Succeeded";
             $this->_batchLog[] = "Subscribe Batch {$batch}: {$batchResult['error_count']} Failed";
             if ($batchResult['error_count']) {
                 $this->_batchErrors["Subscribe Batch {$batch}"] = $batchResult['errors'];
             }
         }
     }
 }
示例#3
0
 $email = $_POST['newsletter-email'];
 if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
     echo '<div class="alert error">Please enter a valid email address</div>';
 } else {
     require_once 'MCAPI.class.php';
     require_once 'config.php';
     //contains apikey
     $api = new MCAPI($apikey);
     $batch[] = array('EMAIL' => $email, 'FNAME' => 'Joe');
     $optin = true;
     //yes, send optin emails
     $up_exist = true;
     // yes, update currently subscribed users
     $replace_int = false;
     // no, add interest, don't replace
     $vals = $api->listBatchSubscribe($listId, $batch, $optin, $up_exist, $replace_int);
     if ($api->errorCode) {
         echo "<div class='alert error'>Sorry we couldn't add your email address.</div>";
         $error = "Mailchimp: Failed to add a email,\n";
         $error .= "code:" . $api->errorCode . "\n";
         $error .= "msg :" . $api->errorMessage . "\n";
         error_log($error);
     } else {
         // Log Errors to php_error_log
         foreach ($vals['errors'] as $val) {
             $error = "Mailchimp: Failed to add a email,\n";
             if (isset($val['email_address'])) {
                 $error .= $val['email_address'] . " failed\n";
             }
             $error .= "code:" . $val['code'] . "\n";
             $error .= "msg :" . $val['message'] . "\n";
示例#4
0
文件: sync.php 项目: rodhoff/MNW
 function sync_all()
 {
     $mainframe = JFactory::getApplication();
     $db = JFactory::getDBO();
     JHTMLBehavior::keepalive();
     $listId = JRequest::getVar('listid', 0, '', 'string');
     /////
     $query = 'SELECT userid FROM #__joomailermailchimpintegration WHERE listid = "' . $listId . '"';
     $db->setQuery($query);
     $exclude = $db->loadResultArray();
     $exclude = implode('","', $exclude);
     $exclude = '"' . $exclude . '"';
     $query = 'SELECT id FROM #__users WHERE id NOT IN (' . $exclude . ') and block = 0';
     $db->setQuery($query);
     $data = $db->loadObjectList();
     $elements = count($data);
     $params = JComponentHelper::getParams('com_joomailermailchimpintegration');
     $MCapi = $params->get('params.MCapi');
     $MC = new MCAPI($MCapi);
     $MCerrorHandler = new MCerrorHandler();
     // gather custom fields data
     $db = JFactory::getDBO();
     $query = "SELECT * FROM #__joomailermailchimpintegration_custom_fields WHERE listid = '" . $listId . "' ";
     $db->setQuery($query);
     $customFields = $db->loadObjectList();
     if (!isset($customFields[0])) {
         $customFields = false;
     }
     $m = 0;
     $successCount = $errorcount = $msgErrorsCount = 0;
     $msg = $msgErrors = false;
     $step = 100;
     //	foreach ($data as $dat){
     for ($x = 0; $x < count($data); $x += $step) {
         $k = 0;
         $batch = array();
         for ($y = $x; $y < $x + $step; $y++) {
             $dat = $data[$y];
             if ($dat) {
                 $user = $this->getModel('sync')->getUser($dat->id);
                 $batch[$k]['EMAIL'] = $user[0]->email;
                 // name
                 $names = explode(' ', $user[0]->name);
                 if ($names[0] && $names[1]) {
                     $batch[$k]['FNAME'] = $names[0];
                     for ($i = 1; $i < count($names); $i++) {
                         $batch[$k]['LNAME'] .= $names[$i] . ' ';
                     }
                 } else {
                     $batch[$k]['FNAME'] = $user[0]->name;
                 }
                 $custom = array();
                 if ($customFields) {
                     foreach ($customFields as $field) {
                         if ($field->framework == 'CB') {
                             $query = "SELECT " . $field->dbfield . " FROM #__comprofiler WHERE user_id = '" . $user[0]->id . "' ";
                         } else {
                             $query = "SELECT value FROM #__community_fields_values WHERE field_id = " . $field->dbfield . " AND user_id = '" . $user[0]->id . "' ";
                         }
                         $db->setQuery($query);
                         $fieldValue = $db->loadResult();
                         if ($field->framework == 'CB') {
                             $fieldValue = str_replace('|*|', ',', $fieldValue);
                         }
                         if ($field->framework == 'JS') {
                             $fieldValue = substr($fieldValue, strlen($fieldValue) - 1) == ',' ? $fieldValue = substr($fieldValue, 0, -1) : $fieldValue;
                             if ($fieldValue == NULL) {
                                 $fieldValue = '';
                             }
                         }
                         $batch[$k]['GROUPINGS'][] = array('id' => (int) $field->grouping_id, 'groups' => $fieldValue);
                     }
                 }
                 $query = 'INSERT INTO #__joomailermailchimpintegration (userid,email,listid) VALUES ("' . $user[0]->id . '", "' . $user[0]->email . '", "' . $listId . '")';
                 $db->setQuery($query);
                 $db->execute();
                 $k++;
             } else {
                 break;
             }
         }
         if ($batch) {
             $optin = false;
             // do not send optin emails
             $updateExisting = true;
             // yes, update currently subscribed users
             $replaceInterests = true;
             // false = add interest, don't replace
             $result = $MC->listBatchSubscribe($listId, $batch, $optin, $updateExisting, $replaceInterests);
             $successCount = $successCount + $result['success_count'];
             if ($result['error_count']) {
                 foreach ($result['errors'] as $e) {
                     $tmp = new stdClass();
                     $tmp->errorCode = $e['code'];
                     $tmp->errorMessage = $e['message'];
                     $errorMsg .= '"' . $MCerrorHandler->getErrorMsg($tmp) . '", ';
                     $query->getQuery(true);
                     $query->delete($db->qn('#__joomailermailchimpintegration'))->where($db->qn('listid') . ' = ' . $db->q($listId))->where($db->qn('email') . ' = ' . $db->q($e['row']['EMAIL']));
                     $db->setQuery($query, 0, 1);
                     $db->execute();
                 }
                 $msgErrorsCount += $result['error_count'];
             }
         }
     }
     if ($errorMsg) {
         $msgErrors = substr($errorMsg, 0, -2);
         $msgErrors = ' (' . $msgErrorsCount . ' ' . JText::_('JM_ERRORS') . ': ' . $msgErrors . ')';
     }
     $msg = $successCount . ' ' . JText::_('JM_RECIPIENTS_SAVED') . $msgErrors;
     $this->app->enqueueMessage($msg);
     $this->app->redirect('index.php?option=com_joomailermailchimpintegration&view=sync');
 }
示例#5
0
                }
            }
            if ($do_update) {
                $to_add[] = $merge_vars;
            }
        }
    }
}
if ($DEBUG && !empty($to_add)) {
    bam("TO ADD / UPDATE:");
    bam($to_add);
    bam("========================");
}
if (!empty($to_add) && !$DRYRUN) {
    if (count($to_add) > 15) {
        $api->listBatchSubscribe($list_id, $to_add, false, true);
        if (!empty($api->errorMessage)) {
            trigger_error("Mailchimp API Error calling listBatchSubscribe(): " . $api->errorMessage, E_USER_ERROR);
        }
    } else {
        // listBatchSubscribe doesn't always update all the merge vars correctly (perhaps if there's a case variation
        // in the email address) so when there's not too many we call listSubscribe individually
        foreach ($to_add as $add) {
            if (!$api->listSubscribe($list_id, $add['EMAIL'], $add, 'html', FALSE, TRUE, FALSE, false)) {
                trigger_error("listSubscribe returned false: " . $api->errorMessage);
            }
        }
    }
}
// Then, for all list members, check if they are in the report members list and if not add them to the "remove" list.
$list_members = $api->listMembers($list_id, 'subscribed', null, 0, 10000);
 /**
  * Import customers into the selected Mailchimp list
  */
 public function importCustomers()
 {
     // Get List id
     $list_id = Tools::getValue('list');
     if (!Tools::isSubmit('list') || !$list_id) {
         $this->message = array('text' => $this->l('List is required! Please select one.'), 'type' => 'error');
         return;
     }
     // Get customers type
     $all_customers = Tools::getValue('all-user') ? true : false;
     // Get mailchimp fields
     $fields = Tools::getValue('fields');
     // Get Customers list
     $customers = Customer::getCustomers();
     // Creating import array
     $list = array();
     foreach ($customers as $customer_key => $customer) {
         // Get customer data
         $customer_details = new Customer($customer['id_customer']);
         // Populate customer array
         if ($all_customers) {
             $list[$customer_key]['EMAIL'] = $customer_details->email;
             if (isset($fields[$list_id])) {
                 foreach ($fields[$list_id] as $key => $field) {
                     // mailchimp tag = customer field
                     $list[$customer_key][$key] = $customer_details->{$field};
                 }
             }
         } else {
             if (!$all_customers && $customer_details->newsletter) {
                 $list[$customer_key]['EMAIL'] = $customer_details->email;
                 if (isset($fields[$list_id])) {
                     foreach ($fields[$list_id] as $key => $field) {
                         // mailchimp tag = customer field
                         $list[$customer_key][$key] = $customer_details->{$field};
                     }
                 }
             }
         }
     }
     // listBatchSubscribe configuration
     $optin = Tools::getValue('optin') ? true : false;
     //send optin emails
     $up_exist = Tools::getValue('update_users') ? true : false;
     //update currently subscribed users
     $replace_int = true;
     // Import customers
     $mailchimp = new MCAPI($this->api_key, $this->ssl);
     $import = $mailchimp->listBatchSubscribe($list_id, $list, $optin, $up_exist, $replace_int);
     // Process response
     if ($mailchimp->errorCode) {
         $this->message = array('text' => $this->l('Mailchimp error code:') . ' ' . $mailchimp->errorCode . '<br />' . $this->l('Milchimp message:') . ' ' . $mailchimp->errorMessage, 'type' => 'error');
         return;
     } else {
         $this->message['text'] = $this->l('Successfull imported:') . ' <b>' . $import['add_count'] . '</b><br />';
         $this->message['text'] .= $this->l('Successfull updated:') . ' <b>' . $import['update_count'] . '</b><br />';
         if ($import['error_count'] > 0) {
             $this->message['text'] .= $this->l('Error occured:') . ' <b>' . $import['error_count'] . '</b><br />';
             foreach ($import['errors'] as $error) {
                 $this->message['text'] .= '<p style="margin-left: 15px;">';
                 $this->message['text'] .= $error['email'] . ' - ' . $error['code'] . ' - ' . $error['message'];
                 $this->message['text'] .= '</p>';
             }
             $this->message['type'] = 'warn';
         }
     }
 }
示例#7
0
}
/**************** MailChimp method ************************/
if ($_SETTINGS['store_to_mailchimp']) {
    if (@$_POST['fields'][$_SETTINGS['email_field_name']] && $_SETTINGS['mailchimp']['apikey'] && $_SETTINGS['mailchimp']['listId']) {
        include_once 'mailChimp/MCAPI.class.php';
        $MCAPI = new MCAPI($_SETTINGS['mailchimp']['apikey']);
        $arr = array('EMAIL' => $_POST['fields'][$_SETTINGS['email_field_name']]);
        if ($_SETTINGS['first_name_field_name']) {
            $arr['FNAME'] = @$_POST['fields'][$_SETTINGS['first_name_field_name']];
        }
        if ($_SETTINGS['last_name_field_name']) {
            $arr['LNAME'] = @$_POST['fields'][$_SETTINGS['last_name_field_name']];
        }
        $MCAPI_batch[] = $arr;
        $MCAPI_optin = true;
        //yes, send optin emails
        $MCAPI_up_exist = true;
        // yes, update currently subscribed users
        $MCAPI_replace_int = false;
        // no, add interest, don't replace
        $MCAPI_vals = $MCAPI->listBatchSubscribe($_SETTINGS['mailchimp']['listId'], $MCAPI_batch, $MCAPI_optin, $MCAPI_up_exist, $MCAPI_replace_int);
        if ($MCAPI->errorCode) {
            $ret['error'] = 1;
        }
    } else {
        $ret['error'] = 1;
    }
}
header('Content-type: application/json; charset=utf-8');
header('Cache-Control: no-cache');
echo json_encode($ret);