function viewAction() { $id = AF::get($this->params, 'campaign_id', FALSE); if (!($modelCampaign = Campaign::model()->restrictions()->findByPk($id))) { throw new AFHttpException(0, 'incorrect_id'); } $clearArray = array(); $this->filter($clearArray); $pagination = new Pagination(array('action' => $this->action, 'controller' => $this->controller, 'params' => $this->params, 'ajax' => true)); $models = AFActiveDataProvider::models('Pixel', $this->params, $pagination); $dataProvider = $models->getAll(); $filterFields = $models->getoutFilterFields($clearArray); // set ajax table if (AF::isAjaxRequestModels()) { $this->view->includeFile('_table', array('application', 'views', 'pixels'), array('access' => $this->access, 'controller' => $this->controller, 'dataProvider' => $dataProvider, 'pagination' => $pagination, 'filterFields' => $filterFields)); die; } $affiliates = Affiliate::model()->restrictions()->findAllInArray(); Assets::js('jquery.form'); Assets::css('jquery-ui'); Assets::js('jquery-ui'); Assets::js('ajax_table'); Assets::js('af_input_field'); $this->addToPageTitle(__('pixels')); $this->render('view', array('dataProvider' => $dataProvider, 'pagination' => $pagination, 'campaign_id' => AF::get($this->params, 'campaign_id'), 'affiliates' => $affiliates, 'modelCampaign' => $modelCampaign)); }
function newretentionAction() { $clearArray = array('campaign_id', 'aff_id'); $this->filter($clearArray); if (!isset($this->params['dates_r'])) { $dataFrom = mktime(0, 0, 0, date("m") - 1, date("d"), date("Y")); $fromDate = date("d.m.Y", $dataFrom); $today = date("d.m.Y"); $this->params['dates_r'] = $fromDate . '-' . $today; } if (!isset($this->params['initial_dates'])) { $fromDate = date("d.m.Y", time() - 777600); $today = date("d.m.Y"); $this->params['initial_dates'] = $fromDate . '-' . $today; } if (!isset($this->params['billing_cycle'])) { $this->params['billing_cycle'] = 1; } $pagination = new Pagination(array('action' => $this->action, 'controller' => $this->controller, 'params' => $this->params)); $models = AFActiveDataProvider::models('Retention', $this->params, $pagination); $report = $models->getForGraph(); $filterFields = $models->getoutFilterFields($clearArray, array('dates_r', 'initial_dates')); $campaigns = Campaign::model()->cache()->findAllInArray(); $affiliates = Affiliate::model()->cache()->findAllInArray(); Assets::css('jquery-ui'); Assets::js('//code.jquery.com/ui/1.10.3/jquery-ui.js'); Assets::js('dateRange/jquery.daterange'); Assets::js('//www.google.com/jsapi'); //<script type="text/javascript" src="https://www.google.com/jsapi"></script> $this->addToPageTitle(__('sales_by_retention_chart')); $this->render('newretention', array('report' => $report, 'campaigns' => $campaigns, 'affiliates' => $affiliates, 'filterFields' => $filterFields)); }
function viewAction() { $clearArray = array('flags'); $this->filter($clearArray); if (empty($this->params)) { $today = date("d.m.Y"); $this->params['dates'] = $today . '-' . $today; } $pagination = new Pagination(array('action' => $this->action, 'controller' => $this->controller, 'params' => $this->params, 'ajax' => true)); $models = AFActiveDataProvider::models('ProspectEmail', $this->params, $pagination); $dataProvider = $models->getAll(); $filterFields = $models->getoutFilterFields($clearArray, array('dates')); // set ajax table if (AF::isAjaxRequestModels()) { $this->view->includeFile('_table', array('application', 'views', 'emails'), array('access' => $this->access, 'controller' => $this->controller, 'dataProvider' => $dataProvider, 'pagination' => $pagination, 'filterFields' => $filterFields)); die; } $campaigns = Campaign::model()->cache()->findAllInArray(); $templates = Template::model()->cache()->findAllInArray(); $flags = ProspectEmail::getEmailFlags(); /* $campaignsFilter = $models->getFilterCampaigns(); $templatesFilter = $models->getFilterTemplates(); $flagsFilter = $models->getFilterFlags(); */ Assets::css('jquery-ui'); Assets::js('jquery-ui'); Assets::js('dateRange/jquery.daterange'); Assets::js('ajax_table'); Assets::js('af_input_field'); $this->addToPageTitle(__('prospect_emails')); $this->render('view', array('dataProvider' => $dataProvider, 'pagination' => $pagination, 'models' => $models, 'filterFields' => $filterFields, 'campaigns' => $campaigns, 'templates' => $templates, 'flags' => $flags)); }
public function getCampaignNumber() { $name = Yii::app()->user->guestName; if (strpos($name, 'uest') == 0) { return false; } // только для гостя if (isset($_REQUEST['campaignId'])) { $campaignId = (int) $_REQUEST['campaignId']; $campaign = Campaign::model()->findByPk($campaignId); $orderId = 0; if (isset($_REQUEST['orderId'])) { $orderId = (int) $_REQUEST['orderId']; } if (!$orderId) { return $campaign_id; } $order = Zakaz::model()->find('id=:id', array(':id' => $orderId)); if ($campaign) { $domains = explode(',', $campaign->domains); $domain = $domains[0]; $_SERVER['SERVER_NAME'] = $domain; return true; } } $campaigns = Campaign::model()->findAll(); foreach ($campaigns as $campaign) { $domains = explode(',', $campaign->domains); $domain = $domains[0]; $_SERVER['SERVER_NAME'] = $domain; if ($this->getCampaignNumber()) { return true; } } }
function viewAction() { $clearArray = array('campaign_id', 'aff_id'); $this->filter($clearArray); $pagination = new Pagination(array('action' => $this->action, 'controller' => $this->controller, 'params' => $this->params, 'ajax' => true)); $models = AFActiveDataProvider::models('Prospect', $this->params, $pagination); $dataProvider = $models->getAll(); $filterFields = $models->getoutFilterFields($clearArray); // set ajax table if (AF::isAjaxRequestModels()) { $this->view->includeFile('_table', array('application', 'views', 'prospects'), array('access' => $this->access, 'controller' => $this->controller, 'dataProvider' => $dataProvider, 'pagination' => $pagination, 'filterFields' => $filterFields, 'ajax' => true)); die; } /* $prospects = $models->getAll(); $countries = $models->getCountries(); $campaignsFilter = $models->getCampaignsCountProspects(); $afids = $models->getAfids(); */ $affiliates = Affiliate::model()->cache()->findAllInArray(); $countries = Country::model()->cache()->findAllInArray(); $campaigns = Campaign::model()->cache()->findAllInArray(); Assets::js('ajax_table'); Assets::js('af_input_field'); $this->addToPageTitle('Prospects'); $this->render('view', array('dataProvider' => $dataProvider, 'pagination' => $pagination, 'models' => $models, 'filterFields' => $filterFields, 'affiliates' => $affiliates, 'countries' => $countries, 'campaigns' => $campaigns)); }
public static function search_by_domain($domain) { $orgz = Campaign::model()->findAll("domains like '%{$domain}%'"); if (count($orgz) == 1) { return $orgz[0]; } else { return false; } }
public function actionExport($id) { $Campaign = Campaign::model()->findByPk($_GET['campaign_id']); if (!$Campaign->hasBeenRun) { throw new CHttpException('404', 'Not found'); } // check campaign has been run if (!$Campaign->hasBeenRun) { throw new CHttpException('403', 'Forbidden'); // not possible. Forbidden. } $CampaignGroup = CampaignGroup::model()->findByAttributes(array('id' => $id, 'campaign_id' => $Campaign->id)); if (is_null($CampaignGroup)) { throw new CHttpException('404', 'Not found'); } $Criteria = new CDbCriteria(); $Criteria->compare('`t`.`campaign_id`', $Campaign->id); $Criteria->compare('`t`.`group_id`', $id); $Criteria->with = array('contact'); $Criteria->order = '`t`.`group_id` ASC'; $CampaignContacts = CampaignContact::model()->findAll($Criteria); // build the csv $rows = array(); $outcomeColumns = array(); foreach ($CampaignGroup->outcomes as $Outcome) { // will be a url or NULL so fine $outcomeColumns[$Outcome->name] = $Outcome->url; } $headings = array('contact_warehouse_id' => 'insider_id', 'salutation' => 'Prefix', 'first_name' => 'Forename', 'last_name' => 'Surname', 'email' => 'Email', 'phone' => 'Telephone', 'mobile' => 'Mobile', 'dob' => 'Date of Birth', 'address_line_1' => 'Address Line 1', 'address_line_2' => 'Address Line 2', 'address_line_3' => 'Address Line 3', 'address_line_4' => 'Address Line 4', 'address_town' => 'Town', 'address_postcode' => 'Postcode', 'address_county' => 'County', 'culture_segment' => 'Culture Segment', 'level_of_engagement' => 'Level of Engagement'); // build each row foreach ($CampaignContacts as $CampaignContact) { $row = array(); // use headings to get data foreach ($headings as $key => $value) { $row[$value] = $CampaignContact->contact->{$key}; } $rows[] = array_merge($row, array_values($outcomeColumns)); } // stick headers on the start after adding outcome names to it array_unshift($rows, array_values(array_merge($headings, array_keys($outcomeColumns)))); $cleanGroupName = preg_replace(array("@[^a-z0-9\\-\\s]@i", "@\\s+@", "@\\-{2,}@"), array("", "-", "-"), $CampaignGroup->name) . '-' . date("Y-m-d"); $csv = fopen('php://output', 'w'); header("Expires: Tue, 03 Jul 2001 06:00:00 GMT"); header("Cache-Control: max-age=0, no-cache, must-revalidate, proxy-revalidate"); header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); header('Content-Encoding: UTF-8'); header('Content-type: text/csv; charset=UTF-8'); // disposition / encoding on response body header("Content-Disposition: attachment;filename=" . $cleanGroupName . ".csv"); header("Content-Transfer-Encoding: binary"); foreach ($rows as $column) { fputcsv($csv, $column); } fclose($csv); //echo $csv; exit; }
public static function getAttachedGatewayByPrn($parent_order_id, $attach_campaign_id, $ps = null) { if (!$parent_order_id || !$attach_campaign_id) { return 0; } // get gateway of parent order $order = Order::model()->fillFromDbPk($parent_order_id); if (!$order) { return 0; } // load attached campaign info $campaign = Campaign::model()->fillFromDbPk($attach_campaign_id); if (!$campaign) { return 0; } $db = self::$_msql = SafeMySQL::getInstance(); for ($c = 0; $c < 3; $c++) { // in case there are gateways but none are set to current alter the query // IF THERE ARE NO CURRENT OR ACTIVE GATEWAYS THEN DEFAULT TO THE FIRST GATEWAY IN THE LIST SO AT LEAST THE ORDER CAN BE BILLED if ($c == 0) { $and = "AND pg.flags = 'cur'"; } else { if ($c == 1) { $and = "AND pg.flags != 'off'"; } else { $and = ''; } } if (strlen($ps)) { $and .= " AND g.system_code = ?s"; } $sql = "SELECT \n\t\t\t\t\t pg.gateway_id\n\t\t\t\tFROM \n\t\t\t\t\tprofiles_gateways as pg\n\t\t\t\t\tLEFT JOIN gateways as g USING(gateway_id)\n\t\t\t\t\tleft JOIN gateway_limits as l on (pg.method_id = l.method_id) and (pg.gateway_id = l.gateway_id)\n\t\t\t\tWHERE \n\t\t\t\t\tg.routing_number = ?s\n\t\t\t\t\tand pg.profile_id = ?i\n\t\t\t\t\tAND pg.method_id = ?i\n\t\t\t\t\t" . $and . "\n\t\t\t\tORDER BY `gateway_rank` ASC\n\t\t\t\tLIMIT 1"; if (strlen($ps)) { $result = $db->getOne($sql, $order->gateway->routing_number, $campaign->profile_id, $order->payment->method_id, $ps); } else { $result = $db->getOne($sql, $order->gateway->routing_number, $campaign->profile_id, $order->payment->method_id); } if (!empty($result)) { return $result; } } return false; }
public static function updateSites($campaignID) { $modelCampaign = Campaign::model()->with('domain')->cache()->findByPk($campaignID); if (!$modelCampaign) { return false; } $db = SafeMySQL::getInstance(); $sql = "SELECT c.`url`,\n c.`campaign_id`,\n c.`country_id`,\n c.`currency_id`\n FROM `campaigns` as c\n WHERE c.`domain_id` = ?i"; $campaigns = $db->getAll($sql, $modelCampaign->domain_id); $rArray = array(); $cIDs = array(); foreach ($campaigns as $campaign) { $cIDs[] = $campaign['campaign_id']; $rArray[$campaign['campaign_id']] = array('main' => array('path' => $campaign['url'], 'campaign_id' => $campaign['campaign_id'], 'country_id' => $campaign['country_id'], 'currency_id' => $campaign['currency_id']), 'products' => array(), 'custom_fields' => array()); $sql = "SELECT `name`, `value`\n FROM `site_variables`\n WHERE (`domain_id`=?i AND`campaign_id`=?i)\n OR (`domain_id`=?i AND `campaign_id` IS NULL)\n OR (`domain_id` IS NULL AND `campaign_id` IS NULL)"; $customFields = $db->getAll($sql, $modelCampaign->domain_id, $campaign['campaign_id'], $modelCampaign->domain_id); if ($customFields) { foreach ($customFields as $field) { $rArray[$campaign['campaign_id']]['custom_fields'][$field['name']] = $field['value']; } } } $sql = "SELECT p.`product_id`,\n p.`prodcat_id`,\n p.`product_name`,\n p.`product_price`,\n p.`product_weight`,\n p.`product_next_id`,\n p.`subscription_days`,\n cp.`campaign_id`\n FROM `products` as p\n JOIN `campaigns_products` as cp USING (`product_id`)\n WHERE cp.`campaign_id` IN (?a)\n AND cp.`enabled` = 1\n AND cp.`upsell_id` IS NULL"; $products = $db->getAll($sql, $cIDs); if ($products) { foreach ($products as $product) { $campaignID = $product['campaign_id']; unset($product['campaign_id']); array_push($rArray[$campaignID]['products'], $product); } } $siteApi = new SiteApi(); if (!$siteApi->createFile(json_encode($rArray))) { //save an error to the log file //.. return false; } $siteApi->domain = $modelCampaign->domain->url; $siteApi->update(); }
function viewAction() { $clearArray = array(); $this->filter($clearArray); $pagination = new Pagination(array('action' => $this->action, 'controller' => $this->controller, 'params' => $this->params, 'ajax' => true)); $models = AFActiveDataProvider::models('Campaign', $this->params, $pagination); //$dataProvider = $models->getAll(); $dataProvider = $models->cache()->getMethod('getAll'); $filterFields = $models->getoutFilterFields($clearArray, array('dates')); // set ajax table if (AF::isAjaxRequestModels()) { $this->view->includeFile('_table', array('application', 'views', 'campaigns'), array('access' => $this->access, 'controller' => $this->controller, 'dataProvider' => $dataProvider, 'pagination' => $pagination, 'filterFields' => $filterFields)); die; } $campaignsFilter = Campaign::model()->cache()->restrictions()->findAllInArray(); // useful UI components for popup dialogs and things of that nature. added to use a dialog popup on the single campaign clone action Assets::js('jquery-ui'); Assets::js('ajax_table'); Assets::css('jquery-ui'); $this->addToPageTitle('Campaigns'); $this->render('view', array('dataProvider' => $dataProvider, 'campaignsFilter' => $campaignsFilter, 'pagination' => $pagination, 'models' => $models, 'filterFields' => $filterFields)); }
public function run($args) { exit; date_default_timezone_set("Europe/London"); print "Getting campaigns to process \n"; $CampaignCollection = Campaign::model()->with('query')->findAll(array("condition" => "processing = 0 AND status = :status AND invite = 1", "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 . " \n"; } $command = Yii::app()->db->createCommand(); $command->update('campaign', array("processing" => 1), array('in', 'id', $campaignIDs)); foreach ($CampaignCollection as $Campaign) { $InviteEmail = new InviteEmail(); $InviteEmail->send($Campaign); $Campaign->processing = 0; $Campaign->save(true, array("processing")); print "Completed processing " . $Campaign->id . " \n"; $Campaign->refresh(); print "Status of campaign was " . $Campaign->getStatusText() . "\n\n"; } }
public function run($args) { exit('Use no.2 command'); ini_set('memory_limit', '4G'); $start = microtime(true); print "\n\n"; print 'Running email de-duperer' . "\n\n"; sleep(1); $QueuedCampaigns = Campaign::model()->findAll(array("condition" => "processing = 0 AND status = :status", "params" => array(":status" => Campaign::STATUS_QUEUED))); $totalInvitesDeleted = 0; $invitesDeleted = []; print sizeof($QueuedCampaigns) . ' campaigns to process' . "\n\n"; foreach ($QueuedCampaigns as $QueuedCampaign) { print 'Looking up Campaign ' . $QueuedCampaign->id . "...\n"; $Invites = Invite::model()->with('store')->findAll(array('condition' => 'query_id != :qid', 'params' => array(':qid' => $QueuedCampaign->query_id))); $previouslyInvited = array(); print 'Building invite array...' . "\n"; foreach ($Invites as $k => $Invite) { $previouslyInvited[] = $Invite->store->email; if ($k % 1000 == 0) { print '.'; } } unset($Invites); sleep(1); print " DONE!\n\n"; sleep(1); print sizeof($previouslyInvited) . ' previously invited contacts' . "\n"; // Dupecheck this campaign $results = Invite::model()->with("store")->findAll(array('condition' => 'campaign_id = :campaign_id', 'params' => array(':campaign_id' => $QueuedCampaign->id))); print sizeof($results) . ' contacts in this invite campaign' . "\n"; $emails = []; if (sizeof($results)) { foreach ($results as $Invite) { $emails[$Invite->id] = $Invite->store->email; } } unset($results); // LOCAL DUPES /* print 'Finding duplicates within this campaign' . "\n"; sleep(1); $arrayCountValues = array_count_values($emails); $localDuplicates = 0; foreach($arrayCountValues as $arrayCount) { if($arrayCount > 1) { $localDuplicates++; } } print 'Duplicates local to this campaign: ' . $localDuplicates . "\n\n"; */ // Global dupes print 'Finding duplicates in entire invite set' . "\n"; $arrayIntersect = array_intersect($emails, $previouslyInvited); unset($previouslyInvited); print 'Dupes found: ' . sizeof($arrayIntersect) . "\n"; foreach ($arrayIntersect as $inviteID => $dupeEmail) { //print 'Deleting duplicate Invite ID: ' . $inviteID . ' for ' . $dupeEmail . "\n"; // $InviteToDelete = Invite::model()->findByPk($inviteID); // $InviteToDelete->delete(); if (!in_array($inviteID, $invitesDeleted)) { $totalInvitesDeleted++; $invitesDeleted[] = $inviteID; } } print "\n\n\n"; print 'COMPLETE' . "\n"; print "\n\n\n"; unset($emails); unset($arrayIntersect); } print 'Total invites deleted: ' . $totalInvitesDeleted . "\n\n"; $RemainingInvites = Invite::model()->count(array('condition' => "date > '2015-01-01' AND status = 0")); print 'Invites remaining to be sent: ' . $RemainingInvites . "\n\n"; print 'Peak memory usage: ' . memory_get_peak_usage(true) / 1024 / 1024 . "MB\n\n\n"; $end = microtime(true); print 'Script ran in ' . round($end - $start, 4) . ' seconds' . "\n\n"; // Alternate with SQL $Invites = Yii::app()->db->createCommand("\n\t\t\n\t\tSELECT i.id, s.email, count(s.email) AS c FROM invite i\n\n\t\tLEFT JOIN store s ON i.store_id = s.id\n\t\t\n\t\tWHERE i.date > '2015-01-01'\n\t\t\n\t\tGROUP BY s.email HAVING c > 1\n\t\t\n\t\t")->queryAll(); print 'Invites to remove using SQL query: ' . sizeof($Invites) . "\n\n"; }
function cloneAction() { if (isset($_POST['clone'])) { $campaigns = Campaign::model()->cache()->findAllInArray(); AF::setJsonHeaders('json'); echo json_encode(array('campaigns' => $campaigns)); die; } if (isset($_POST['ajax'])) { AF::setJsonHeaders('json'); $campaign_id = AF::get($_POST, 'campaign_id', 0); $campprod_ids = AF::get($_POST, 'campship_id', 0); if (!$campprod_ids && !$campaign_id) { Message::echoJsonError(__('campship_id_not_found')); } $campprods = explode(',', $campprod_ids); $message = array(); $newIDs = array(); $isMany = count($campprods) > 1 ? true : false; $isThisCampaign = true; foreach ($campprods as $id) { $model = new CampaignShipping(); if (!$model->findByPk($id)) { if ($isMany) { continue; } Message::echoJsonError(__('campship_not_found')); } if ($model->campaign_id != $campaign_id) { $model->campaign_id = $campaign_id; $isThisCampaign = false; } if (!$model->cloneModel()) { if ($isMany) { continue; } Message::echoJsonError($model->errors2string); } $newID = $newIDs[] = $model->getPkValue(); $message[] = __('campship_cloned') . ' <a href="' . $this->controller . '/view/campaign_id=' . $campaign_id . '">' . __('view_campaign') . ' (ID: ' . $newID . ')</a><br>'; unset($model); } if (!$message) { Message::echoJsonError(__('campship_not_cloned')); } $message = implode($message); $newIDs = implode(',', $newIDs); $v = array('message' => $message); if ($isThisCampaign) { $v['newid'] = $newIDs; } Message::echoJsonSuccess($v); } }
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"; } }
/** * Sends an individual email to an item in a campaign/newsletter list. * * @param type $campaignId * @param type $itemId */ public function actionMailIndividual($campaignId, $itemId) { $this->itemId = $itemId; $this->campaign = Campaign::model()->findByPk($campaignId); $email = $this->recipient->email; if ($this->campaign instanceof Campaign && $this->listItem instanceof X2ListItem) { $this->sendIndividualMail(); $this->response['fullStop'] = $this->fullStop; $status = $this->status; // Actual SMTP (or elsewise) delivery error that should stop the batch: $error = $status['code'] != 200 && $this->undeliverable || $this->fullStop; $this->response['status'] = $this->status; $this->respond($status['message'], $error); } else { $this->respond(Yii::t('marketing', 'Specified campaign does not exist.'), 1); } }
public function getCampaigns() { /*$where = $this->unsetWhereKey('campaign_id', 'stext', 'LL_order_id', 'order_id', 'fname', 'lname', 'customer_id', 'email', 'product_id'); $unionSelect = ''; if( !empty($this->searchFields['campaign_id']) ) { $tempArray = explode(',', $this->searchFields['campaign_id']); foreach($tempArray as $value) { $unionSelect .= " UNION SELECT {$value},0"; } } $join = $this->join; if($this->searchFields['recurring_orders']) $join .= " JOIN `orders_products` as op USING (`order_id`)"; if($this->searchFields['country_id']) $join .= " JOIN `campaigns` as c USING (`campaign_id`)"; if($this->searchFields['method_id']) $join .= " LEFT JOIN `payments` as p USING (`payment_id`)"; $sql = "SELECT c.`url`, c.`campaign_name`, o.* FROM `campaigns` c JOIN (SELECT * FROM ( SELECT `campaign_id`, COUNT(*) AS `count` FROM `orders` o LEFT JOIN `addresses` as ad USING (`address_id`) ?p WHERE ?p GROUP BY `campaign_id` {$unionSelect}) `o2` GROUP BY `campaign_id` ) o USING (`campaign_id`) ORDER BY `campaign_id` DESC"; // This used to be order by 'url' but I changed it to campaign_id DESC for /orders/view //fb(self::$_msql->parse($sql, $this->join, $where)); $result=self::$_msql->getAll($sql, $join, $where); return AF::userAccess()->array2RestrictionArray('campaign_id', $result);*/ return Campaign::model()->cache()->findAllInArray(); }
public function attachedOrder($order, $campaign_id, $isPayment = false) { $this->wsType = 'a1'; $this->intervalCheck = false; $this->isPayment = $isPayment; $this->newCustomer = false; $this->order = $order; $this->campaign = Campaign::model()->fillFromDbPk($campaign_id); if (!$this->campaign) { return false; } // creating child / parent link in the DB $parent_id = $this->order->order_id; // clear the model and update $this->order->getCopyModel(); $this->order->parent_id = $parent_id; $this->order->status = 'new'; $this->order->created = $this->order->updated = 'NOW():sql'; //date("Y-m-d H:i:s"); $this->order->campaign_id = $this->campaign->campaign_id; $this->order->click_id = NULL; // check for parent test order if ($this->order->isFlag('test')) { $this->test = true; } $this->order->removeFlags(); if ($this->isPayment) { $this->order->addFlags('pay'); } else { $this->order->flags = ''; } // set test if ($this->test) { $this->order->addFlags('test'); } $this->order->ship_with = NULL; // set default values. will be updated further down the script $this->order->amount_product = '0'; $this->order->amount_shipping = '0'; $this->order->payment_total = '0'; $this->order->amount_refunded = '0'; $this->order->pixel_fired = '0'; $this->order->shipping_id = 19; // Free Shipping $this->order->billing_cycle = 0; // check for test cc //if (stripos($this->order->payment->method->method_ref,'cc_') !== false && $this->order->payment->cc_number == Config::get()->payments->pacnet['testCC']) { if (isset($this->order->payment) && stripos($this->order->payment->method->method_ref, 'cc_') !== false && ($this->order->payment->num4 == strlen(Config::get()->payments->pacnet['testCC']) && $this->order->payment->num2 == substr(Config::get()->payments->pacnet['testCC'], 0, 6) && $this->order->payment->num3 == substr(Config::get()->payments->pacnet['testCC'], strlen(Config::get()->payments->pacnet['testCC']) - 4, 4))) { $this->order->addFlags('test'); $this->test = true; } // Check to see if a gateway assigned to the attached campaign has the same PRN info as the gateway used in the main order. if so, use it $gid = @ProfileGateways::getAttachedGatewayByPrn($parent_id, $campaign_id); // if not, Grab Current gateway. will be checked again before payment is submitted. if (!$gid) { // ignore payment system type for this // RENABLE THIS FOR ATTACH ORDERS? QUESTION. $gid = @ProfileGateways::getCurrentGatewayByIds($this->campaign->profile_id, $this->order->payment->method_id); if (!$gid) { $gid = 0; } // set to 0. the batch job that bills the orders can deal with this } // if we have a new gateway, use it. if not keep the old one from the parent order if ($gid) { $this->order->gateway_id = $gid; } unset($gid); // save order if (!$this->order->save(true, null, false)) { fb($this->order->getErrors()); //$this->apiError('attached order error - ' . $this->order->geterrors2string()); return false; } //Save order logs $orderLogModel = new OrderLog(); $orderLogModel->order_id = $parent_id; $orderLogModel->user_id = 0; $orderLogModel->action = 26; $orderLogModel->notes = $this->order->order_id; $orderLogModel->save(); // load products for the attach campaign $campProducts = new CampaignProducts('CampaignProduct'); $campProducts->load($this->campaign->campaign_id); $pArray = array(); foreach ($campProducts->products as $p) { $pArray[] = $p->product_id; } $this->post = array(); $this->post['product_id'] = implode(',', $pArray); unset($campProducts); $this->buildProducts(); $amount = $this->amount_product; // set shipping info // I'm assuming that since this is an attach campaign there's only one shipping option $campShip = new CampaignShippings('CampaignShipping'); $campShip->load($this->campaign->campaign_id); $this->order->shipping_id = $campShip->shipping[0]->shipping_id; $this->order->amount_shipping = $campShip->selectedShipping($this->order->shipping_id)->amount_initial; // catch for missing shipping id if (!$this->order->shipping_id) { $this->order->shipping_id = 19; $this->order->amount_shipping = '0.00'; } unset($campShip); // set total $this->order->amount_product = $amount ? $amount : '0.00'; $this->order->status = 'new'; $total = $this->order->amount_product + $this->order->amount_shipping; // check to make sure there is an amount > 0 for this order, // if not: 1. don't bill 2. Remove flags 3. set ok status if (!$total) { $this->isPayment = false; $this->order->status = 'ok'; $this->order->removeFlags('pay'); $this->order->addFlags('paid'); Event::setEvents($this->order->order_id, 8, false); } else { if ($total && !isset($this->order->payment->payment_id)) { $isPayment = false; } } // save if (!$this->order->save(true, null, false)) { fb($this->order->getErrors()); //$this->apiError('attached error - ' . $this->order->geterrors2string()); return false; } // process payment if ($this->isPayment) { $paymentAPI = new PaymentAPI(); $paymentAPI->setModel($this->order->payment); // !$this->order->isFlag('test') && $this->order->payment->cc_number != Config::get()->payments->pacnet['testCC'] if (!$this->test) { $paymentResponse = $paymentAPI->payOrder($this->order->order_id, $total); //fb($paymentAPI); //fb($paymentResponse); } // what happened? if ($this->test || $paymentResponse->getstatus() != 'error') { // ACCEPTED $this->order->status = 'ok'; if (@stripos($this->order->payment->method->method_ref, 'cc_') !== false) { // APPROVED / PAID // was the payment actually processed, like a cc_debit? set order total $this->order->removeFlags('pay'); $this->order->addFlags('paid'); $this->order->payment_total = $total; } else { //fb('NOT ACTUALLY PROCESSED'); // was the payment accepted by the gateway, but not actually processed? //$this->order->addFlags('paid'); } $this->order->updated = 'NOW():sql'; //date("Y-m-d H:i:s"); if (!$this->order->save(true, null, false)) { //this should never happen. just log the error, email the team and assume its all good for the customer fb($this->order->getErrors()); } Event::setEvents($this->order->order_id, 8, false); // NEED TO UPDATE THE GATEWAY LIMITS AND STATUS. WOULD BE BENEFICIAL IS THIS WERE SOMEHOW AN ASYNCHRONOUS FUNCTION CALL //if(!$this->order->isFlag('test')) { //$pg = new ProfileGateways('ProfileGateway'); //$o = clone $this->order; //$pg->processGatewayRoutingByOrder($o); //unset($o); //} } else { // DECLINED $this->order->status = 'error'; $this->order->updated = 'NOW():sql'; //date("Y-m-d H:i:s"); if (!$this->order->save(true, null, false)) { //this should never happen. log the error, email the team and send the user back to the payment details page fb($this->order->getErrors()); } return false; } } elseif ($total) { // isPayment is false, but there is an amount that needs to be billed. set up order for cron payment //$this->order->status = 'ok'; $this->order->addFlags('pay'); if (!$this->order->save(true, null, false)) { //this should never happen. just log the error, email the team and assume its all good for the customer fb($this->order->getErrors()); } } return $this->order->order_id; }
break; case QueryQuestion::OPTION_ARTFORM: if (is_null($Artforms)) { $Artforms = Artform::model()->findAll(array('index' => 'id', 'order' => 'title ASC')); } print ' ' . $CultureSegments[$row->query_option]->title; break; case QueryQuestion::OPTION_LOE: if (is_null($LevelsOfEngagement)) { $LevelsOfEngagement = QueryQuestion::model()->levelsOfEngagement(); } print ' ' . $LevelsOfEngagement[$row->query_option]; break; case QueryQuestion::OPTION_CAMPAIGN: if (is_null($Campaigns)) { $Campaigns = Campaign::model()->with('query')->findAll(array('condition' => 'invite = 0', 'index' => 'id')); } print ' ' . $Campaigns[$row->query_option]; break; default: print ' ' . $row->query_number; break; } ?> </td> </tr> <?php } ?> </table> </div>
public function validateCampaignId($attr) { $value = $this->{$attr}; $campaign = Campaign::model()->findByPk($value); if (!$campaign) { throw new CHttpException(400, Yii::t('marketing', 'Bad request')); } $this->campaign = $campaign; }
public function loadModel($id) { $Model = Campaign::model()->findByPk($id); if ($Model === null) { throw new CHttpException(404, 'The requested page does not exist.'); } return $Model; }
function approvalsAction() { $clearArray = array(); $this->filter($clearArray); if (!isset($this->params['dates'])) { $today = date("d.m.Y"); $this->params['dates'] = $today . '-' . $today; } if (!isset($this->params['sort_by'])) { $this->params['sort_by'] = 'bank_name'; } if (!isset($this->params['sort'])) { $this->params['sort'] = 'asc'; } $models = AFActiveDataProvider::models('Order', $this->params); $dataProvider = $models->getApprovalsReport(); $filterFields = $models->getoutFilterFields($clearArray, array('dates')); //=Order::$FilterFields // Download a csv file if (isset($this->params['download_csv'])) { Csv::printArray($dataProvider); } // set an ajax table if (AF::isAjaxRequestModels()) { $this->view->includeFile('_approvals_table', array('application', 'views', 'reports'), array('access' => $this->access, 'controller' => $this->controller, 'dataProvider' => $dataProvider, 'filterFields' => $filterFields, 'ajax' => true)); die; } $campaigns = Campaign::model()->cache()->findAllInArray(); $countries = Country::model()->cache()->findAllInArray(); $this->addToPageTitle(__('section_name_approvals_report')); Assets::css('jquery-ui'); Assets::js('jquery-ui'); Assets::js('dateRange/jquery.daterange'); Assets::js('ajax_table'); Assets::js('af_input_field'); $this->render('approvals', array('dataProvider' => $dataProvider, 'filterFields' => $filterFields, 'campaigns' => $campaigns, 'countries' => $countries)); }
/** * Send mail for any active campaigns, in a batch. * * This method is made public and static to allow it to be called from elsewhere, * without instantiation. * * @param integer $id The ID of the campaign to return status messages for */ public static function sendMail($id = null, $t0 = null) { self::$batchTime = $t0 === null ? time() : $t0; $admin = Yii::app()->settings; $messages = array(); $totalSent = 0; try { // Get all campaigns that could use mailing $campaigns = Campaign::model()->findAllByAttributes(array('complete' => 0, 'active' => 1, 'type' => 'Email'), 'launchdate > 0 AND launchdate < :time', array(':time' => time())); foreach ($campaigns as $campaign) { try { list($sent, $errors) = self::campaignMailing($campaign); } catch (CampaignMailingException $e) { $totalSent += $e->return[0]; $messages = array_merge($messages, $e->return[1]); $messages[] = Yii::t('marketing', 'Successful email sent') . ': ' . $totalSent; $wait = $admin->emailInterval + $admin->emailStartTime - time(); return array('wait' => $wait, 'messages' => $messages); } $messages = array_merge($messages, $errors); $totalSent += $sent; if (time() - self::$batchTime > Yii::app()->settings->batchTimeout) { break; } } if (count($campaigns) == 0) { $messages[] = Yii::t('marketing', 'There is no campaign email to send.'); } } catch (Exception $e) { $messages[] = $e->getMessage(); } $messages[] = $totalSent == 0 ? Yii::t('marketing', 'No email sent.') : Yii::t('marketing', 'Successful email sent') . ': ' . $totalSent; $wait = $admin->emailInterval + $admin->emailStartTime - time(); return array('wait' => $wait, 'messages' => $messages); }
break; // Culture Segment // Culture Segment case QueryQuestion::OPTION_CS: $CultureSegment = CultureSegment::model()->findByPk($query_option); print $CultureSegment->name; break; // Artforms // Artforms case QueryQuestion::OPTION_ARTFORM: $Artforms = Artform::model()->findByPk($query_option); print $Artform->title; // Level of engagement // Level of engagement case QueryQuestion::OPTION_LOE: $LevelsOfEngagement = QueryQuestion::model()->levelsOfEngagement(); foreach ($LevelsOfEngagement as $LOEid => $LOEName) { if ($query_option == $LOEid) { print $LOEName; } } break; // Campaign // Campaign case QueryQuestion::OPTION_CAMPAIGN: $Campaign = Campaign::model()->findByPk($query_option); print $Campaign->name; break; } ?> </span>
/** * /invites/:id * Allows user to add email content and send invitation emails to contacts */ public function actionSend() { if ((int) $_GET['campaign_id']) { // existing sent invite $Campaign = Campaign::model()->findByPk($_GET['campaign_id']); if (is_null($Campaign)) { throw new CHttpException(404, 'Not found'); } $Query = $Campaign->query; } else { throw new CHttpException(404, 'Page not found.'); } if ((int) $Campaign->status !== Campaign::STATUS_NOT_RUN) { // Redirect to view $this->redirect(array('invite/view', 'campaign_id' => $Campaign->id)); exit; } // Set scenario for validation $Campaign->scenario = 'inviteSend'; if (isset($_POST['Campaign'])) { if ($Campaign->validate()) { // Are we testing, or sending for real? if (isset($_POST['test'])) { if (!strlen($_POST['Campaign']['email_test_recipient'])) { $Campaign->addError('email_test_recipient', 'Test email recipient cannot be blank'); } else { $InviteEmail = new InviteEmail(); $InviteEmail->sendTest($_POST['Campaign']['email_test_recipient'], $Campaign->invite_email_subject, $Campaign->invite_email_body); $this->refresh(); } } elseif (!in_array($Campaign->status, array(Campaign::STATUS_QUEUED, Campaign::STATUS_HAS_BEEN_RUN))) { // Set Campaign as queued for sending $Campaign->status = Campaign::STATUS_QUEUED; $Campaign->save(true, array('status')); // Set a flash message Yii::app()->user->setFlash('success', 'The invite has been queued for sending'); $this->redirect(array('invite/index')); } } } $this->breadcrumbs = array('Invites' => array('index'), $Campaign->name => array('edit', 'campaign_id' => $Campaign->id), 'Sending Options'); $this->render('send', array('Campaign' => $Campaign, 'Query' => $Query, 'results' => $results)); }
public function createAction() { $model = new Order(); $_POST['status'] = 'new'; $isPayment = AF::get($_POST, 'is_payment'); if (!$isPayment) { $_POST['ps'] = 'pn'; $_POST['payment_method'] = 'cc_debit'; } /*$rtr = ''; foreach($_POST as $k => $v) { $rtr .= " '".$k."' => '".$v."',"; } Message::echoJsonSuccess($rtr);*/ // is this also a new customer creation if (isset($_POST['newCus']) && $_POST['newCus'] == 1) { $cust = new Customer(); $this->performAjaxValidation($cust); //$shipData = (array)json_decode($_POST['shipAddr']); //$shipData['address_type'] = 'shipping'; $this->performAjaxFormFieldsValidation($_POST, explode(',', 'shipping_fname,shipping_lname,shipping_phone,shipping_address1,shipping_city,shipping_state_id,shipping_country_id,shipping_zip')); //Message::echoJsonSuccess('made it2'); if (!$_POST['billingSameAsShipping']) { //$billData = (array)json_decode($_POST['billAddr']); //$billData['address_type'] = 'billing'; $this->performAjaxFormFieldsValidation($_POST, explode(',', 'billing_fname,billing_lname,billing_phone,billing_address1,billing_city,billing_state_id,billing_country_id,billing_zip')); } $orderRules = "campaign_id,gateway_id,shipping_id,amount_product,amount_shipping,payment_total"; } else { $_POST['newCus'] = 0; $orderRules = "customer_id,campaign_id,gateway_id,shipping_id,amount_product,amount_shipping,payment_total,address_id,billing_address_id"; if (isset($_POST['address_id']) && empty($_POST['billing_address_id'])) { $_POST['billing_address_id'] = $_POST['address_id']; } // before billing validation } // Uncomment the following line if AJAX validation is needed $this->performAjaxValidation($model, explode(',', $orderRules)); if (isset($_POST['model']) && $_POST['model'] == 'Order') { $isOrderPay = $this->access->actionAccess('order_is_pay') ? (bool) AF::get($_POST, 'is_payment') : false; $_POST['is_payment'] = $isOrderPay ? 1 : 0; // JSON success and error commands handled in the WS functions $ws = new WS(); $ws->crmInit($_POST); $ws->process(); } $orderID = AF::get($this->params, 'order_id', false); $prospectID = AF::get($this->params, 'prospect_id', false); $payments = array(); if ($orderID) { $model->fillFromDbPk($orderID); // if we use clone model then we cannot grab related fields $model->getCopyModel(); $orderProducts = OrderProducts::getProductsArrayByOrder($model->order_id); $payment_methods = ProfileGateways::getMethodsByProfileGateway($model->campaign->profile_id, $model->gateway_id); $cPayments = new Payments('Payment'); $payments = $cPayments->getResultsByCustomerId($model->customer_id, false); } elseif ($prospectID) { $modelProspect = Prospect::model()->findByPk($prospectID); if (!$modelProspect) { throw new AFHttpException(0, 'incorrect_id'); } $model->customer_id = $modelProspect->customer_id; $model->campaign_id = $modelProspect->campaign_id; $model->address_id = $modelProspect->address_id; $orderProducts = array(); $payment_methods = array(); } else { $orderProducts = array(); $payment_methods = array(); } $productModel = new Product(); $products = $productModel->getAvailableByCampaignID($model->campaign_id); $countryModel = new Country(); $languages = $countryModel->getLanguages(); $states = $model->country_id ? State::model()->getStatesByCID($model->country_id) : array(); //$model->country_ids='de,ir'; $countries = $countryModel->getCountries(); $campaigns = Campaign::model()->cache()->findAllInArray(); $shippingModel = new Shipping(); $shipping = $shippingModel->getAvailableByCampaignID($model->campaign_id); $modelGateways = new Gateway(); //$modelGateways->getGateways() $gateways = $orderID ? $modelGateways->getAvailableByCampaignID($model->campaign_id) : array(); $methods = Method::model()->cache()->findAllInArray(); $fields_expyear = array('current_year' => date("Y"), 'last_year' => date("Y") + 12); Assets::js('jquery.form'); Assets::js('jquery.autocomplete'); Assets::js('as24.bind-1.3.5.min'); Assets::js('jquery-ui'); Assets::css('jquery-ui'); $this->addToPageTitle('Create Order'); $this->render('create', array('model' => $model, 'products' => $products, 'languages' => $languages, 'campaigns' => $campaigns, 'states' => $states, 'countries' => $countries, 'fields_expyear' => $fields_expyear, 'shipping' => $shipping, 'gateways' => $gateways, 'orderProducts' => $orderProducts, 'payment_methods' => $payment_methods, 'payments' => $payments, 'methods' => $methods)); }