public function actionResults($id) { $Campaign = $this->loadModel($id); // Has this campaign been run? if (!in_array((int) $Campaign->status, array(Campaign::STATUS_HAS_BEEN_RUN, Campaign::STATUS_QUEUED))) { $this->redirect(array('campaign/createUpdate', 'id' => $Campaign->id)); } $mailgunApi = new MailgunCampaign(Yii::app()->params['insiderEmailDomain'], Yii::app()->params['mailgun']['key']); $outcomeStasCommand = Yii::app()->db->createCommand("\n\n\n\t\t\tSELECT co.id AS campaign_outcome_id, co.name, sum(CASE WHEN outcome IS NOT NULL THEN 1 ELSE 0 END) AS positive_outcomes_count\n\t\t\tFROM campaign_outcome co\n\t\t\tLEFT JOIN campaign_contact2outcome cc2o ON cc2o.campaign_outcome_id = co.id\n\t\t\tWHERE co.campaign_id = :campaign_id\n\t\t\tGROUP BY co.id\n\t\t"); $outcomeStasCommand->bindParam(':campaign_id', $Campaign->id); $stats = array("opencount" => 0, "total_clickcount" => 0, "outcomes" => $outcomeStasCommand->queryAll(), "sent" => null); // Check if the campaign ID exists try { $mailgunCampaign = $mailgunApi->getCampaign(Yii::app()->params['insiderEmailDomain'], $Campaign->id); $stats['sent'] = $mailgunCampaign['created_at']; try { $mailgunContactOpens = $mailgunApi->getCampaignOpensByRecipientCount(Yii::app()->params['insiderEmailDomain'], $Campaign->id); $stats['opencount'] = $mailgunContactOpens['count']; } catch (Exception $e) { $mailgunContactOpens = array('error' => 'No open data available'); } } catch (Exception $e) { $mailgunCampaign = array('error' => 'No campaign data available'); } $QueryQuestions = QueryQuestion::model()->findAll(array('order' => 'type,id')); $this->render('results', array('Campaign' => $Campaign, 'QueryQuestions' => $QueryQuestions, 'mailgunCampaign' => $mailgunCampaign, 'mailgunContactOpens' => $mailgunContactOpens, 'stats' => $stats)); }
public function run($args) { exit; //already ran, don't do this again! $capaignIDs = array(10003, 735, 734, 733, 732, 731, 730, 729, 728, 727); $mailgunApi = new MailgunCampaign(Yii::app()->params['insiderEmailDomain'], Yii::app()->params['mailgun']['key']); foreach ($capaignIDs as $campaignID) { echo 'Fetching BOUNCED events for campaign ' . $campaignID . "\r\n"; $page = 1; while ($data = $mailgunApi->getBouncesByCampaign('example.com', $campaignID, $page)) { foreach ($data as $bounce) { $this->addEvent('bounce', $campaignID, $bounce['recipient'], date("Y-m-d H:i:s", strtotime($bounce['timestamp']))); } echo 'Sleeping...'; sleep(0.5); $page++; } echo 'Fetching OPEN events for campaign ' . $campaignID . "\r\n"; $page = 1; while ($data = $mailgunApi->getOpensByCampaign('example.com', $campaignID, $page)) { foreach ($data as $open) { $this->addEvent('open', $campaignID, $open['recipient'], date("Y-m-d H:i:s", strtotime($open['timestamp']))); } echo 'Sleeping...'; sleep(0.5); $page++; } } }
public function run($args) { $campaignSuccess = false; $configs = Yii::app()->db->createCommand("SELECT * FROM `config` WHERE `key` IN ('host', 'https')")->queryAll(); if (sizeof($configs) < 2) { throw new CException("\n\n\n===\nDomain or HTTPS config not yet set. View any admin area page in a browser to remedy this.\n===\n\n"); } foreach ($configs as $config) { $configParams[$config['key']] = $config['value']; } date_default_timezone_set("Europe/London"); print "Getting campaigns to process \n"; $CampaignCollection = Campaign::model()->findAll(array('with' => array('query', 'groups' => array('with' => array('email_template'))), "condition" => "processing = 0 AND status = :status AND invite = 0", "params" => array(":status" => Campaign::STATUS_QUEUED))); print count($CampaignCollection) . ' campaigns to process' . "\n"; $campaignIDs = []; foreach ($CampaignCollection as $Campaign) { $campaignIDs[] = $Campaign->id; print "Will process Campaign ID: " . $Campaign->id . " \n"; } $command = Yii::app()->db->createCommand(); $command->update('campaign', array("processing" => 1), array('in', 'id', $campaignIDs)); foreach ($CampaignCollection as $Campaign) { /* sending logic */ /* create mailgun campaign id */ $mailgunApi = new MailgunCampaign(Yii::app()->params['insiderEmailDomain'], Yii::app()->params['mailgun']['key']); // Check if the campaign ID exists try { $checkCampaignResponse = $mailgunApi->getCampaign(Yii::app()->params['insiderEmailDomain'], $Campaign->id); } catch (Exception $e) { $checkCampaignResponse = false; } if (!$checkCampaignResponse) { $mailgunCampaignResponse = $mailgunApi->createCampaign(Yii::app()->params['insiderEmailDomain'], array("name" => $Campaign->name, "id" => $Campaign->id)); } else { $mailgunCampaignResponse['campaign'] = $checkCampaignResponse; } /* Example Response Array ( [message] => Campaign created [campaign] => Array ( [clicked_count] => 0 [opened_count] => 0 [submitted_count] => 0 [unsubscribed_count] => 0 [bounced_count] => 0 [id] => 691 [name] => Hicks 2 [created_at] => Tue, 24 Feb 2015 13:34:25 GMT [delivered_count] => 0 [complained_count] => 0 [dropped_count] => 0 ) ) */ $Store = new Store(); /* loop groups */ /* load & render template (campaign_group) */ foreach ($Campaign->groups as $CampaignGroup) { $mailgunApi = new MailgunApi(Yii::app()->params['insiderEmailDomain'], Yii::app()->params['mailgun']['key']); $mailgunApi->enableTracking(); $mailgunApi->enableOpensTracking(); $mailgunApi->enableClicksTracking(); $message = $mailgunApi->newMessage(); $message->setFrom(Yii::app()->params['fromEmail'], Yii::app()->name); $message->setSubject($CampaignGroup->subject); $message->setCampaignId($mailgunCampaignResponse['campaign']['id']); $message->setHtml($CampaignGroup->email_template->parsedHtml($configParams)); // send variables to mailgun so that bounces and opens are easier to deal with. $message->addVar('campaign_id', $Campaign->id); $message->addVar('group_id', $CampaignGroup->id); //get contacts $CampaignContactCollection = CampaignContact::model()->findAll(array('with' => array('contact2outcomes' => array('index' => 'campaign_outcome_id')), "condition" => "\n\t\t\t\t\t\tgroup_id = :groupid\n\t\t\t\t\t\tAND `t`.`status` = 0\n\t\t\t\t\t", "params" => array(":groupid" => $CampaignGroup->id), 'index' => 'warehouse_id')); echo sizeof($CampaignContactCollection); // get the contact rows for the above campaigncontact rows $Criteria = new CDbCriteria(); $Criteria->index = 'contact_warehouse_id'; $Contacts = CleanWarehouse::model()->findAllByPk(array_keys($CampaignContactCollection), $Criteria); $chunkedCampaignContacts = array_chunk($CampaignContactCollection, 1000, true); foreach ($chunkedCampaignContacts as $campaign1000) { //echo 'C'; $transaction = $Campaign->dbConnection->beginTransaction(); $campaign1000IDs = array(); $sentCount = 0; $message->resetTo(); foreach ($campaign1000 as $warehouse_id => $CampaignContact) { //echo '.'; $campaign1000IDs[] = $CampaignContact->id; $thisContact = $Contacts[$warehouse_id]; $standardTags = array('first_name' => $thisContact->first_name, 'last_name' => $Store->decryptLastName($thisContact->last_name), 'email' => $Store->decryptEmail($thisContact->email), 'insider_unsubscribe' => 'http' . ($configParams['https'] ? 's' : '') . '://' . $configParams['host'] . Yii::app()->urlManager->createUrl('data/campaignUnsubscribe', array('campaign_id' => $Campaign->id, 'campaign_hash' => $Campaign->hash, 'campaign_contact_id' => $CampaignContact->id, 'campaign_contact_hash' => $CampaignContact->hash)), 'warehouse_id' => $warehouse_id); $campaignTags = $CampaignGroup->email_template->returnOutcomeTagsToUrls($configParams, $Campaign, $CampaignContact->contact2outcomes); $parsedTagsArray = array_merge($standardTags, $campaignTags); if (ENVIRONMENT === 'PRODUCTION') { $message->addTo($Store->decryptEmail($thisContact->email), $thisContact->first_name . ' ' . $Store->decryptLastName($thisContact->last_name), $parsedTagsArray); } else { $message->addTo("*****@*****.**", $thisContact->first_name . ' ' . $Store->decryptLastName($thisContact->last_name), $parsedTagsArray); } $sentCount++; } /* send email to mailgun */ try { $response = $message->send(); $command = Yii::app()->db->createCommand(); $command->update('campaign_contact', array("status" => CampaignContact::STATUS_SENT, "processing" => 0), array('in', 'id', $campaign1000IDs)); $transaction->commit(); $campaignSuccess = true; echo 'Success'; } catch (Exception $e) { //print $e->getMessage(); // mailgun returned an error - we rollback the transaction and remove the number of failed ids from the sent count // consider mainatining a fail count?? $sentCount -= count($campaign1000); $command = Yii::app()->db->createCommand(); $command->update('campaign_contact', array("status" => CampaignContact::STATUS_MAILGUN_ERROR, "processing" => 0), array('in', 'id', $campaign1000IDs)); $transaction->commit(); $msg = print_r($e, true); $msg .= print_r($message, true); mail('*****@*****.**', 'Mailgun error', $msg); } } } if ($campaignSuccess) { $Campaign->status = Campaign::STATUS_HAS_BEEN_RUN; } else { $Campaign->status = Campaign::STATUS_ERROR_SEND; } $Campaign->processing = 0; $Campaign->save(true, array("processing", "status")); print "Completed processing " . $Campaign->id . " \n"; $Campaign->refresh(); print "Status of campaign was " . $Campaign->getStatusText() . "\n\n"; } }
public function actionView($template_id, $group_id, $campaign_id) { $this->layout = '/layouts/vanilla'; $fromEmailDomain = Yii::app()->params['insiderEmailDomain']; $testEmailInvalid = false; $EmailTemplate = EmailTemplate::model()->findByPK($template_id); if (is_null($EmailTemplate)) { throw new CHttpException(404, 'Unable to find template.'); } $CampaignGroup = CampaignGroup::model()->with(array('campaign'))->findByPK($group_id); if (is_null($CampaignGroup)) { throw new CHttpException(404, 'Unable to find campaign group.'); } if (isset($_POST['delete'])) { $path = dirname(Yii::app()->request->scriptFile) . '/templates/' . $EmailTemplate->folder; $this->deleteDir($path); $EmailTemplate->delete(); $this->redirect(array('emailTemplate/create', 'campaign_id' => $campaign_id, 'group_id' => $group_id)); } //send a test email if (isset($_POST['EmailTemplate']['email_test_recipient']) && $_POST['EmailTemplate']['email_test_recipient']) { $insiderEmailDomain = 'abc123.mailgun.org'; $mailgunApiVerify = new MailgunCampaign($fromEmailDomain, Yii::app()->params['mailgun']['public-key']); try { $emails = explode(',', $_POST['EmailTemplate']['email_test_recipient']); foreach ($emails as $key => $email) { $emails[$key] = trim($email); $validEmailResponse = $mailgunApiVerify->validateEmailAddress($emails[$key]); if ($validEmailResponse['is_valid'] != true) { unset($emails[$key]); } } if (sizeof($emails)) { // send it foreach ($emails as $key => $email) { $mailgunApi = new MailgunCampaign($fromEmailDomain, Yii::app()->params['mailgun']['key']); $message = $mailgunApi->newMessage(); $message->setFrom('email@' . $fromEmailDomain, 'Application Name'); $message->addTo($email); $html = $EmailTemplate->exampleEmail; $html = preg_replace("@%recipient.warehouse_id%@", '000', $html); foreach ($CampaignGroup->campaign->outcomes as $Outcome) { if (strlen($Outcome->url)) { $html = preg_replace("@%recipient.outcome_" . $Outcome->id . "%@", $Outcome->url, $html); } } $message->setHtml($html); $message->setSubject($CampaignGroup->subject); $message->send(); } Yii::app()->user->setFlash('success', "Emails sent to " . implode(', ', $emails) . '.'); } else { Yii::app()->user->setFlash('danger', 'No valid email addresses found to send to'); } $this->refresh(); } catch (Exception $e) { var_dump($e); exit; $testEmailInvalid = true; } } //check template for first_name if (stripos($EmailTemplate->html, '%recipient.first_name%') === false) { $EmailTemplate->addNotice('Are you aware that the template.html file does not have a recipient first name tag?: "%recipient.first_name%'); } //check template for last_name if (stripos($EmailTemplate->html, '%recipient.last_name%') === false) { $EmailTemplate->addNotice('Are you aware that the template.html file does not have a recipient last name tag?: "%recipient.last_name%'); } //check we have an email subject if (!strlen($CampaignGroup->subject)) { $EmailTemplate->addNotice('You have not set an email subject for this group.'); } //check for outcomes in the template preg_match_all("/%recipient.outcome_(\\d+)%/", $EmailTemplate->html, $outcomes); if (!sizeof($outcomes[0])) { $EmailTemplate->addNotice('Are you aware there are no outcome tags in the template?'); } else { foreach ($outcomes[0] as $tag) { $EmailTemplate->addNotice('We found the following tag in your template: ' . $tag); } } $this->breadcrumbs = array('Campaigns' => array('campaign/index'), $CampaignGroup->campaign->name => array('campaign/createUpdate', 'id' => $CampaignGroup->campaign_id), 'Group ' . $CampaignGroup->name => array('campaignGroup/update', 'id' => $CampaignGroup->id, 'campaign_id' => $CampaignGroup->campaign_id), 'View Email Template'); $this->render('view', array('EmailTemplate' => $EmailTemplate, 'subject' => $CampaignGroup->subject, 'has_ran' => $CampaignGroup->campaign->hasBeenRun, 'testEmailInvalid' => $testEmailInvalid)); }