public function executeCreate(sfWebRequest $request) { if (!($this->getUser()->hasCredential(myUser::CREDENTIAL_ADMIN) || StoreTable::value(StoreTable::CAMAPIGN_CREATE_ON))) { return $this->ajax()->alert('', 'You have no right to create a campaign.', '#my_campaigns h3', 'after')->render(); } $form = new NewCampaignNameForm(); $form->bind($request->getPostParameter($form->getName())); if (!$form->isValid()) { return $this->ajax()->form_error_list($form, '#my_campaigns_create', 'after')->render(); } CampaignTable::getInstance()->getConnection()->beginTransaction(); try { $campaign = new Campaign(); $campaign->setName($form->getValue('name')); $campaign->setDataOwner($this->getGuardUser()); $store = StoreTable::getInstance()->findByKey(StoreTable::PRIVACY_AGREEMENT); if ($store) { $campaign->setPrivacyPolicy($store->getField('text')); } $campaign->save(); $cr = new CampaignRights(); $cr->setCampaign($campaign); $cr->setUser($this->getGuardUser()); $cr->setActive(1); $cr->setAdmin(1); $cr->setMember(1); $cr->save(); CampaignTable::getInstance()->getConnection()->commit(); } catch (Exception $e) { CampaignTable::getInstance()->getConnection()->rollback(); return $this->ajax()->alert('', 'DB Error', '#my_campaigns_create', 'after')->render(); } return $this->ajax()->redirectRotue('campaign_edit_', array('id' => $campaign->getId()))->render(); // return $this->ajax()->alert('Campaign created', '', '#my_campaigns_create', 'after')->render(); }
public function setup() { global $current_user; $current_user = SugarTestUserUtilities::createAnonymousUser(); //for the purpose of this test, we need to create a campaign and relate it to a campaign tracker object //create campaign $c = new Campaign(); $c->name = 'CT test ' . time(); $c->campaign_type = 'Email'; $c->status = 'Active'; $timeDate = new TimeDate(); $c->end_date = $timeDate->to_display_date(date('Y') + 1 . '-01-01'); $c->assigned_id = $current_user->id; $c->team_id = '1'; $c->team_set_id = '1'; $c->save(); $this->campaign = $c; //create campaign tracker $ct = new CampaignTracker(); $ct->tracker_name = 'CampaignTrackerTest' . time(); $ct->tracker_url = 'sugarcrm.com'; $ct->campaign_id = $this->campaign->id; $ct->save(); $this->campaign_tracker = $ct; }
public static function createCampaign($id = '') { $time = mt_rand(); $name = 'SugarCampaign'; $campaign = new Campaign(); $campaign->name = $name . $time; $campaign->status = 'Active'; $campaign->campaign_type = 'Email'; $campaign->end_date = '2010-11-08'; if (!empty($id)) { $campaign->new_with_id = true; $campaign->id = $id; } $campaign->save(); self::$_createdCampaigns[] = $campaign; return $campaign; }
/** * Add or edit campaigns * CODE: campaign_create */ public function executeUpdate(sfWebRequest $request) { # security if (!$this->getUser()->hasCredential(array('Administrator'), false)) { $this->getUser()->setFlash("warning", 'You don\'t have permission to access this url ' . $request->getReferer()); $this->redirect('dashboard/index'); } if ($request->getParameter('id')) { $campaign = CampaignPeer::retrieveByPK($request->getParameter('id')); $this->forward404Unless($campaign); $this->title = 'Edit campaign'; $success = 'Campaign information has been successfully changed!'; } else { $campaign = new Campaign(); $this->title = 'Add new campaign'; $success = 'Campaign information has been successfully created!'; } $this->back = $request->getReferer(); $this->form = new CampaignForm($campaign); if ($request->isMethod('post')) { $this->referer = $request->getReferer(); $this->form->bind($request->getParameter('campaign')); if ($this->form->isValid()) { $campaign->setCampaignDecs($this->form->getValue('campaign_decs')); $campaign->setPremiumSku($this->form->getValue('premium_sku')); $campaign->setPremiumMin($this->form->getValue('premium_min')); $campaign->save(); $this->getUser()->setFlash('success', $success); $last = $request->getParameter('back'); if (strstr($last, 'donation/create')) { $back_url = $last; } else { $back_url = 'campaign'; } $this->redirect($back_url); } } else { # Set referer URL $this->referer = $request->getReferer() ? $request->getReferer() : '@campaign'; } $this->campaign = $campaign; }
/** * Create a campaign for all contacts with a certain tag. * * This action will create and save the campaign and redirect the user to * edit screen to fill in the email message, etc. It is intended to provide * a fast workflow from tags to campaigns. * * @param string $tag */ public function actionCreateFromTag($tag) { //enusre tag sanity if (empty($tag) || strlen(trim($tag)) == 0) { Yii::app()->user->setFlash('error', Yii::t('marketing', 'Invalid tag value')); $this->redirect(Yii::app()->request->getUrlReferrer()); } //ensure sacred hash if (substr($tag, 0, 1) != '#') { $tag = '#' . $tag; } //only works for contacts $modelType = 'Contacts'; $now = time(); //get all contact ids from tags $ids = Yii::app()->db->createCommand()->select('itemId')->from('x2_tags')->where('type=:type AND tag=:tag')->group('itemId')->order('itemId ASC')->bindValues(array(':type' => $modelType, ':tag' => $tag))->queryColumn(); //create static list $list = new X2List(); $list->name = Yii::t('marketing', 'Contacts for tag') . ' ' . $tag; $list->modelName = $modelType; $list->type = 'campaign'; $list->count = count($ids); $list->visibility = 1; $list->assignedTo = Yii::app()->user->getName(); $list->createDate = $now; $list->lastUpdated = $now; //create campaign $campaign = new Campaign(); $campaign->name = Yii::t('marketing', 'Mailing for tag') . ' ' . $tag; $campaign->type = 'Email'; $campaign->visibility = 1; $campaign->assignedTo = Yii::app()->user->getName(); $campaign->createdBy = Yii::app()->user->getName(); $campaign->updatedBy = Yii::app()->user->getName(); $campaign->createDate = $now; $campaign->lastUpdated = $now; $transaction = Yii::app()->db->beginTransaction(); try { if (!$list->save()) { throw new Exception(array_shift(array_shift($list->getErrors()))); } $campaign->listId = $list->nameId; if (!$campaign->save()) { throw new Exception(array_shift(array_shift($campaign->getErrors()))); } foreach ($ids as $id) { $listItem = new X2ListItem(); $listItem->listId = $list->id; $listItem->contactId = $id; if (!$listItem->save()) { throw new Exception(array_shift(array_shift($listItem->getErrors()))); } } $transaction->commit(); $this->redirect($this->createUrl('update', array('id' => $campaign->id))); } catch (Exception $e) { $transaction->rollBack(); Yii::app()->user->setFlash('error', Yii::t('marketing', 'Could not create mailing') . ': ' . $e->getMessage()); $this->redirect(Yii::app()->request->getUrlReferrer()); } }
* Contributor(s): ______________________________________.. ********************************************************************************/ require_once 'include/formbase.php'; require_once 'modules/Campaigns/Campaign.php'; $focus = new Campaign(); $focus->retrieve($_POST['record']); if (!$focus->ACLAccess('Save')) { ACLController::displayNoAccess(true); sugar_cleanup(true); } if (!empty($_POST['assigned_user_id']) && $focus->assigned_user_id != $_POST['assigned_user_id'] && $_POST['assigned_user_id'] != $current_user->id) { $check_notify = TRUE; } else { $check_notify = FALSE; } foreach ($focus->column_fields as $field) { if (isset($_POST[$field])) { $value = $_POST[$field]; $focus->{$field} = $value; } } foreach ($focus->additional_column_fields as $field) { if (isset($_POST[$field])) { $value = $_POST[$field]; $focus->{$field} = $value; } } $focus->save($check_notify); $return_id = $focus->id; $GLOBALS['log']->debug("Saved record with id of " . $return_id); handleRedirect($focus->id, $focus->name);
/** * @depends testCreateAndGetCampaignListById */ public function testHtmlContentGetsSavedCorrectly() { $randomData = ZurmoRandomDataUtil::getRandomDataByModuleAndModelClassNames('EmailTemplatesModule', 'EmailTemplate'); $htmlContent = $randomData['htmlContent'][count($randomData['htmlContent']) - 1]; $campaign = new Campaign(); $campaign->name = 'Another Test Campaign Name'; $campaign->supportsRichText = 0; $campaign->status = Campaign::STATUS_ACTIVE; $campaign->fromName = 'Another From Name'; $campaign->fromAddress = '*****@*****.**'; $campaign->fromName = 'From Name2'; $campaign->fromAddress = '*****@*****.**'; $campaign->subject = 'Another Test subject'; $campaign->textContent = 'Text Content'; $campaign->htmlContent = $htmlContent; $campaign->marketingList = self::$marketingList; $this->assertTrue($campaign->save()); $campaignId = $campaign->id; $campaign->forgetAll(); $campaign = Campaign::getById($campaignId); $this->assertEquals($htmlContent, $campaign->htmlContent); }
function emailAction() { $model = new CampaignEmail(); if (isset($_POST['ajax'])) { if (isset($_POST['model']) && $_POST['model'] == 'prospects') { // Uncomment the following line if AJAX validation is needed $this->performAjaxValidation($model); $model->fillFromArray($_POST); /* $model->user_id_created = $this->user->user_id; $model->user_id_updated = $this->user->user_id; $model->updated = 'NOW():sql'; $model->created = 'NOW():sql'; $model->model_uset_id = $this->user->user_id; */ if ($model->save()) { Message::echoJsonSuccess(); } else { Message::echoJsonError(__('prospects_email_not_created') . ' ' . $model->errors2string); } die; } if (isset($_POST['model']) && $_POST['model'] == 'campaigns') { $campaignModel = new Campaign(); $campaignModel->setIsNewRecord(false); $campaignID = AF::get($_POST, 'campaign_id'); $campaignModel->fillFromDbPk($campaignID); $campaignModel->smtp_id = AF::get($_POST, 'smtp_id'); $campaignModel->user_id_updated = $this->user->user_id; $campaignModel->updated = 'NOW():sql'; if ($campaignModel->save(false)) { Message::echoJsonSuccess(__('campaign_updated')); } else { Message::echoJsonError(__('campaign_no_updated')); } die; } } $clearArray = array(); $this->filter($clearArray); $pagination = new Pagination(array('action' => $this->action, 'controller' => $this->controller, 'params' => $this->params, 'ajax' => true)); $models = AFActiveDataProvider::models('CampaignEmail', $this->params, $pagination); $dataProvider = $models->getAll(); $filterFields = $models->getoutFilterFields($clearArray); // set ajax table if (AF::isAjaxRequestModels()) { $this->view->includeFile('_email_table', array('application', 'views', 'prospects'), array('access' => $this->access, 'controller' => $this->controller, 'dataProvider' => $dataProvider, 'pagination' => $pagination, 'filterFields' => $filterFields)); die; } $templates = Template::model()->cache()->findAllInArray(); $smtps = Smtp::model()->cache()->findAllInArray(); $campaignID = AF::get($this->params, 'campaign_id'); $campaignModel = new Campaign(); $campaignModel->fillFromDbPk($campaignID); Assets::js('jquery.form'); $this->addToPageTitle(__('prospect_email')); $this->render('email', array('dataProvider' => $dataProvider, 'pagination' => $pagination, 'models' => $models, 'campaignModel' => $campaignModel, 'templates' => $templates, 'smtps' => $smtps, 'filterFields' => $filterFields)); }
/** * Performs the work of inserting or updating the row in the database. * * If the object is new, it inserts it; otherwise an update is performed. * All related objects are also updated in this method. * * @param PropelPDO $con * @return int The number of rows affected by this insert/update and any referring fk objects' save() operations. * @throws PropelException * @see save() */ protected function doSave(PropelPDO $con) { $affectedRows = 0; // initialize var to track total num of affected rows if (!$this->alreadyInSave) { $this->alreadyInSave = true; // We call the save method on the following object(s) if they // were passed to this object by their coresponding set // method. This object relates to these object(s) by a // foreign key reference. if ($this->aDonor !== null) { if ($this->aDonor->isModified() || $this->aDonor->isNew()) { $affectedRows += $this->aDonor->save($con); } $this->setDonor($this->aDonor); } if ($this->aGiftTypeRelatedByGiftType !== null) { if ($this->aGiftTypeRelatedByGiftType->isModified() || $this->aGiftTypeRelatedByGiftType->isNew()) { $affectedRows += $this->aGiftTypeRelatedByGiftType->save($con); } $this->setGiftTypeRelatedByGiftType($this->aGiftTypeRelatedByGiftType); } if ($this->aCampaign !== null) { if ($this->aCampaign->isModified() || $this->aCampaign->isNew()) { $affectedRows += $this->aCampaign->save($con); } $this->setCampaign($this->aCampaign); } if ($this->aFund !== null) { if ($this->aFund->isModified() || $this->aFund->isNew()) { $affectedRows += $this->aFund->save($con); } $this->setFund($this->aFund); } if ($this->isNew()) { $this->modifiedColumns[] = DonationPeer::ID; } // If this object has been modified, then save it to the database. if ($this->isModified()) { if ($this->isNew()) { $pk = DonationPeer::doInsert($this, $con); $affectedRows += 1; // we are assuming that there is only 1 row per doInsert() which // should always be true here (even though technically // BasePeer::doInsert() can insert multiple rows). $this->setId($pk); //[IMV] update autoincrement primary key $this->setNew(false); } else { $affectedRows += DonationPeer::doUpdate($this, $con); } $this->resetModified(); // [HL] After being saved an object is no longer 'modified' } $this->alreadyInSave = false; } return $affectedRows; }
public function actionAjax() { //this function does one of three things depending on payload //would be better in hindsight to send an "action" command //if we want to save the query if (isset($_POST['save'])) { //if id is set, there we are updating, else it's a new query if (isset($_POST['query_id']) && (int) $_POST['query_id']) { //we are updating $Query = Query::model()->findByPk($_POST['query_id']); } else { $Query = new Query(); $Query->created = date("Y-m-d H:i:s"); } // Is this an invite query? $Query->invite = isset($_POST['invite']) ? 1 : 0; $Query->user_id = Yii::app()->user->id; $Query->name = $_POST['Query']['name']; $Query->description = $_POST['Query']['description']; $Query->JSON = $this->getQueryJSON(); if ($Query->save()) { if (!$_POST['query_id']) { // Creating a Query or an Invite? if ($Query->invite) { // Create a campaign to go with this Query - it has to have one $Campaign = new Campaign(); $Campaign->name = $Query->name; $Campaign->description = $Query->description; $Campaign->query_id = $Query->id; $Campaign->status = Campaign::STATUS_NOT_RUN; $Campaign->processing = 0; if ($Campaign->save()) { $errorOccured = false; // Everything is saved ok. Now run the query and get all the contacts $queryResults = $Query->runInviteContactQuery(); // loop array and add each one to invite table foreach ($queryResults['rows'] as $contact) { // Create a new Invite model $Invite = new Invite(); $Invite->contact_warehouse_id = $contact['contact_warehouse_id']; $Invite->store2contact_id = $contact['store2contact_id']; $Invite->store_id = $contact['store_id']; $Invite->organisation_id = $contact['origin_organisation_id']; $Invite->hash = sha1($contact['contact_warehouse_id'] . $contact['store2contact_id'] . $contact['origin_organisation_id'] . microtime(true) . SHASALT); $Invite->date = date('Y-m-d H:i:s'); $Invite->query_id = $Campaign->query_id; $Invite->campaign_id = $Campaign->id; $Invite->status = Invite::STATUS_UNSENT; $Invite->processing = 0; if (!$Invite->save()) { $errorOccured = true; $errors = print_r($Invite->errors, true); Yii::log('Error saving Invite model: ' . $errors, 'error'); } else { } unset($Invite); } if ($errorOccured) { mail('*****@*****.**', 'Website Error', 'Invite attempted Invite model could not be saved. See Application logs.'); } $Query->num_contacts = sizeof($queryResults['rows']); $Query->save(true, array('num_contacts')); // new. set flash then return request to redirect. Yii::app()->user->setFlash('success', 'The new invite has been created successfully.'); $array = array('success' => true, 'redirect' => $this->createUrl('invite/index')); } else { throw new CHttpException('500', 'Error saving campaign'); } } else { // new. set flash then return request to redirect. //Run query to get count to save. $queryResults = $Query->runCampaignCountQuery(); $Query->num_contacts = $queryResults['count']; $Query->save(true, array('num_contacts')); Yii::app()->user->setFlash('success', 'The new query has been created successfully.'); $array = array('success' => true, 'redirect' => $this->createUrl('query/update', array('id' => $Query->id))); } } else { $queryResults = $Query->runCampaignCountQuery(); $Query->num_contacts = $queryResults['count']; $Query->save(true, array('num_contacts')); $array = array("success" => true, 'id' => $Query->id, 'resultsTotal' => number_format($queryResults['count'])); } } else { $array = array("errors" => $Query->getErrors()); } header('Content-Type: application/json'); print CJSON::encode($array); } else { if (isset($_POST['new-row'])) { $rowNumber = time(); $Question = QueryQuestion::model()->findByPk($_POST['new']['query_choice']); $QueryQuestions = QueryQuestion::model()->findAll(array('order' => 'type,id')); header('Content-Type: application/json'); print json_encode(array('html' => $this->renderPartial('_row', array('Question' => $Question, 'QueryQuestions' => $QueryQuestions, 'and_choice' => $_POST['new']['and_choice'], 'bool_choice' => $_POST['new']['bool_choice'], 'query_choice' => $_POST['new']['query_choice'], 'query_number' => $_POST['new']['query_number'], 'query_option' => $_POST['new']['query_option'], 'rowNumber' => $rowNumber), true))); } else { if (isset($_POST['render'])) { //just render the question options //get the query question with that id $Question = QueryQuestion::model()->findByPk($_POST['id']); //render partial $this->renderPartial('_options', array('Question' => $Question, 'rowNumber' => $_POST['rowNumber'])); } elseif (isset($_POST['results'])) { if ($_POST['query_id']) { $Query = Query::model()->findByPk($_POST['query_id']); if (is_null($Query)) { throw new CHttpException(404, 'Not found'); } $Query->JSON = $this->getQueryJSON(); } else { $Query = new Query(); $Query->JSON = $this->getQueryJSON(); } if (isset($_POST['invite'])) { $queryResults = $Query->runInviteCountQuery(); } else { $queryResults = $Query->runCampaignCountQuery(); } header('Content-Type: application/json'); $queryResults['results'] = number_format($queryResults['count']); unset($queryResults['rows']); // Don't need rows on query page, just extra HTTP traffic print json_encode($queryResults); } else { throw new CHttpException(404, 'The requested page does not exist.'); } } } }
function getAdminInterface() { $this->addJS('/modules/Campaigns/js/voteadmin.js'); $this->addCSS('/modules/Campaigns/css/campaign.css'); switch (@$_REQUEST['section']) { case 'addedit': if ($this->user->hasPerm('addcampaign')) { $campaign = new Campaign(@$_REQUEST['campaign_id']); $form = $campaign->getAddEditForm(); $this->smarty->assign('form', $form); $this->smarty->assign('status', $campaign->getId()); if ($form->isSubmitted() && isset($_REQUEST['submit'])) { if ($form->validate()) { return $this->topLevelAdmin(); } } return $this->smarty->fetch('admin/campaigns_addedit.tpl'); } return $this->smarty->fetch('../../../cms/templates/error.tpl'); case 'campaigndelete': $campaign = new Campaign($_REQUEST['campaign_id']); if ($this->user->hasPerm('addcampaign') && $this->user->getAuthGroup() == $campaign->getGroup() && strpos($campaign->getStatus(), 'pcoming') > 0) { $campaign->delete(); unset($campaign); return $this->topLevelAdmin(); } return $this->smarty->fetch('../../../cms/templates/error.tpl'); case 'viewresults': if ($this->user->hasPerm('viewcampaign')) { $campaign = new Campaign($_REQUEST['campaign_id']); $this->smarty->assign('campaign', $campaign); $campaign->addResultViewer($this->user->getId()); return $this->smarty->fetch('admin/campaign_results.tpl'); } return $this->smarty->fetch('admin/campaign_recips_addedit.tpl'); case 'questionedit': if ($this->user->hasPerm('addcampaign')) { $campaign = new Campaign($_REQUEST['campaign_id']); $this->smarty->assign('campaign', $campaign); if (isset($_REQUEST['choices_submit'])) { if (!is_null(@$_REQUEST['choice'])) { foreach ($_REQUEST['choice'] as $key => $achoice) { if (is_numeric($key)) { $choice = new CampaignChoice($key); if (!empty($achoice['main'])) { $choice->setCampaign($_REQUEST['campaign_id']); $choice->setChoice($achoice['main']); $choice->save(); if (is_array(@$_REQUEST['choice'][$key])) { $choice->createChildren($_REQUEST['choice'][$key]); } } else { $choice->delete(); } } } } if (!is_null(@$_REQUEST['nChoice'])) { if (isset($_REQUEST['nChoice'])) { foreach ($_REQUEST['nChoice'] as $key => $achoice) { if (!empty($achoice['main'])) { $choice = new CampaignChoice(); $choice->setCampaign($_REQUEST['campaign_id']); $choice->setChoice($achoice['main']); $choice->save(); if (is_array(@$_REQUEST['nChoice'][$key])) { $choice->createChildren($_REQUEST['nChoice'][$key]); } } } } } return $this->topLevelAdmin(); } return $this->smarty->fetch('admin/campaign_choices_addedit.tpl'); } return $this->smarty->fetch('../../../cms/templates/error.tpl'); case 'reciplist': return $this->recipTopLevelAdmin(); case 'recipaddedit': if ($this->user->hasPerm('addcampaignrecips')) { if (!is_null(@$_REQUEST['recipient_id'])) { $recipient = new CampaignUser($_REQUEST['recipient_id']); } else { $recipient = new CampaignUser(); $recipient->setGroup($this->user->getAuthGroup()); } $form = $recipient->getAddEditForm(); $this->smarty->assign('form', $form); if ($form->isSubmitted() && isset($_REQUEST['submit'])) { if ($form->validate()) { return $this->recipTopLevelAdmin(); } } return $this->smarty->fetch('admin/campaign_recips_addedit.tpl'); } return $this->smarty->fetch('../../../cms/templates/error.tpl'); case 'recipcsvup': if ($this->user->hasPerm('addcampaignrecips')) { $form = Campaign::getCSVForm(); $this->smarty->assign('form', $form); if ($form->validate() && $form->isSubmitted() && $_POST['submit']) { return $this->recipTopLevelAdmin(); } return $this->smarty->fetch('admin/campaign_csvup.tpl'); } return $this->smarty->fetch('../../../cms/templates/error.tpl'); case 'recipdelete': if ($this->user->hasPerm('addcampaignrecips')) { if (!is_null($_REQUEST['id']) && CampaignUser::exists($_REQUEST['id'])) { $recipient = new CampaignUser($_REQUEST['id']); if ($recipient->getGroup() == $this->user->getAuthGroup()) { $recipient->delete(); unset($_REQUEST['id']); } else { return $this->smarty->fetch('../../../cms/templates/error.tpl'); } } return $this->recipTopLevelAdmin(); } return $this->smarty->fetch('../../../cms/templates/error.tpl'); case 'votesend': if ($this->user->hasPerm('addcampaignrecips')) { $campaign = new Campaign($_REQUEST['campaign_id']); return $campaign->mailOut('votes'); } return 'You do not have permission to perform this action.'; case 'voteprint': if ($this->user->hasPerm('generatereciplist')) { $campaign = new Campaign($_REQUEST['campaign_id']); $campaign->preparePdf(); } return $this->topLevelAdmin(); case 'resultsend': if ($this->user->hasPerm('addcampaignrecips')) { $campaign = new Campaign($_REQUEST['campaign_id']); return $campaign->mailOut('results'); } return 'You do not have permission to perform this action.'; case 'listbilling': if ($this->user->hasPerm('admin')) { $groups = Group::getGroups(); $this->smarty->assign('groups', $groups); return $this->smarty->fetch('admin/billing_list.tpl'); } case 'viewbilling': if ($this->user->hasPerm('admin')) { $group = new Group($_REQUEST['group_id']); $this->smarty->assign('group', $group); $campaigns = Campaign::getCampaigns($_REQUEST['group_id']); $campaignsSorted = array_merge($campaigns['upcoming'], $campaigns['progress'], $campaigns['ended']); $this->smarty->assign('campaigns', $campaignsSorted); return $this->smarty->fetch('admin/billing_view.tpl'); } case 'togglestatus': if ($this->user->hasPerm('admin')) { $group = new Group($_REQUEST['group_id']); if ($group->getStatus() > 0) { $group->setStatus(0); } else { $group->setStatus(1); } $group->save(); } $groups = Group::getGroups(); $this->smarty->assign('groups', $groups); return $this->smarty->fetch('admin/billing_list.tpl'); break; case 'whovoted': if ($this->user->hasPerm('addcampaign')) { $campaign = new Campaign($_REQUEST['campaign_id']); $this->smarty->assign('votedlist', $campaign->userVotedList()); $this->smarty->assign('notvotedlist', $campaign->userVotedList(false)); $this->smarty->assign('campaignName', $campaign->getName()); return $this->smarty->fetch('admin/voted_list.tpl'); } return $this->topLevelAdmin(); case 'archivecampaign': if ($this->user->hasPerm('addcampaign')) { $campaign = new Campaign($_REQUEST['campaign_id']); $campaign->setArchiveStatus(1); $campaign->save(); } return $this->topLevelAdmin(); case 'viewarchive': if ($this->user->hasPerm('viewcampaign')) { $campaigns = Campaign::getCampaigns($this->user->getAuthGroup(), 1, 'endDate ASC'); $this->smarty->assign('campaigns', $campaigns); $this->smarty->assign('company', $this->user->getAuthGroupName()); return $this->smarty->fetch('admin/campaign_archive.tpl'); } return $this->topLevelAdmin(); default: if ($this->user->hasPerm('admin') && !$this->user->hasPerm('viewcampaign')) { header("Location: /admin/Campaigns§ion=listbilling"); } return $this->topLevelAdmin(); } }
/** * @before _secure, changeLayout, _admin */ public function shuffle() { $this->seo(array("title" => "Shuffle Game", "view" => $this->getLayoutView())); $view = $this->getActionView(); if (RequestMethods::post("action") == "campaign") { $shuffle = new \Shuffle(); $shuffle->live = true; $shuffle->save(); $campaign = new \Campaign(array("title" => RequestMethods::post("title"), "description" => RequestMethods::post("description", ""), "image" => $this->_upload("promo_im"), "type" => "shuffle", "type_id" => $shuffle->id)); $campaign->save(); $this->redirect("/config/shuffleitem/" . $shuffle->id); } }
public function postProcess() { //ADD if (Tools::isSubmit('submitAddcampaign')) { parent::validateRules(); if (count($this->errors)) { return false; } // ADD WAY if (!($id_campaign = (int) Tools::getValue('id_campaign')) && empty($this->errors)) { $defaultLanguage = new Language((int) Configuration::get('PS_LANG_DEFAULT')); // Include voucher : // Create campaign : $campaign = new Campaign(); $campaign->name = Tools::getValue('name'); $campaign->email_tpl = Tools::getValue('email_tpl'); $campaign->execution_time_day = Tools::getValue('execution_time_day'); $campaign->execution_time_hour = Tools::getValue('execution_time_hour'); $campaign->voucher_prefix = Tools::getValue('voucher_prefix'); $campaign->voucher_amount = Tools::getValue('voucher_amount'); $campaign->voucher_amount_type = Tools::getValue('voucher_amount_type'); $campaign->voucher_day = Tools::getValue('voucher_day'); $campaign->active = Tools::getValue('active'); // Create email files : $path = _PS_ROOT_DIR_ . '/modules/superabandonedcart/mails/' . $defaultLanguage->iso_code . '/'; if (!file_exists($path)) { if (!mkdir($path, 0777, true)) { $this->errors[] = Tools::displayError('Mails directory could not be created. Please check system permissions'); } } $tpl_file_name = $campaign->getFileName('html'); // create html files $f = fopen($path . $tpl_file_name, 'w'); fwrite($f, $campaign->email_tpl); fwrite($f, PHP_EOL); fclose($f); $tpl_file_name = $campaign->getFileName('txt'); // create txt files $f = fopen($path . $tpl_file_name, 'w'); fwrite($f, strip_tags($campaign->email_tpl)); fwrite($f, PHP_EOL); fclose($f); if (!$campaign->save()) { $this->errors[] = Tools::displayError('An error has occurred: Can\'t save the current object'); } // UPDATE WAY } elseif ($id_campaign = Tools::getValue('id_campaign')) { $defaultLanguage = new Language((int) Configuration::get('PS_LANG_DEFAULT')); // Create campaign : $campaign = new Campaign($id_campaign); $campaign->name = Tools::getValue('name'); $campaign->email_tpl = Tools::getValue('email_tpl'); $campaign->execution_time_day = Tools::getValue('execution_time_day'); $campaign->execution_time_hour = Tools::getValue('execution_time_hour'); $campaign->voucher_prefix = Tools::getValue('voucher_prefix'); $campaign->voucher_amount = Tools::getValue('voucher_amount'); $campaign->voucher_amount_type = Tools::getValue('voucher_amount_type'); $campaign->voucher_day = Tools::getValue('voucher_day'); $campaign->active = Tools::getValue('active'); $path = _PS_ROOT_DIR_ . '/modules/superabandonedcart/mails/' . $defaultLanguage->iso_code . '/'; if (!file_exists($path)) { if (!mkdir($path, 0777, true)) { $this->errors[] = Tools::displayError('Mails directory could not be created. Please check system permissions'); } } $tpl_file_name = $campaign->getFileName('html'); // create html files $f = fopen($path . $tpl_file_name, 'w'); fwrite($f, $campaign->email_tpl); fwrite($f, PHP_EOL); fclose($f); $tpl_file_name = $campaign->getFileName('txt'); // create txt files $f = fopen($path . $tpl_file_name, 'w'); fwrite($f, strip_tags($campaign->email_tpl)); fwrite($f, PHP_EOL); fclose($f); if (!$campaign->save()) { $this->errors[] = Tools::displayError('An error has occurred: Can\'t save the current object'); } } } elseif (Tools::isSubmit('statuscampaign') && Tools::getValue($this->identifier)) { if ($this->tabAccess['edit'] === '1') { if (Validate::isLoadedObject($object = $this->loadObject())) { if ($object->toggleStatus()) { $identifier = (int) $object->id_parent ? '&id_campaign=' . (int) $object->id_parent : ''; Tools::redirectAdmin($this->context->link->getAdminLink('AdminSuperAbandonedCart')); } else { $this->errors[] = Tools::displayError('An error occurred while updating the status.'); } } else { $this->errors[] = Tools::displayError('An error occurred while updating the status for an object.') . ' <b>' . $this->table . '</b> ' . Tools::displayError('(cannot load object)'); } } else { $this->errors[] = Tools::displayError('You do not have permission to edit this.'); } } elseif (Tools::getIsset('deletecampaign') && Tools::getValue($this->identifier)) { $id_campaign = (int) Tools::getValue($this->identifier); $b = new Campaign($id_campaign); $b->delete(); unset($b); } elseif (Tools::getIsset('submitBulkenableSelectioncampaign') && Tools::getValue('campaignBox')) { $ids_banner_deleted = Tools::getValue('campaignBox'); // remove each banner foreach ($ids_banner_deleted as $id) { $b = new Campaign($id); $b->toggleStatus(); unset($b); } } elseif (Tools::getIsset('submitBulkdisableSelectioncampaign') && Tools::getValue('campaignBox')) { $ids_banner_deleted = Tools::getValue('campaignBox'); // remove each banner foreach ($ids_banner_deleted as $id) { $b = new Campaign($id); $b->toggleStatus(); unset($b); } } }
/** * @depends testCreateAndGetCampaignListById */ public function testRequiredAttributes() { $campaign = new Campaign(); $this->assertFalse($campaign->save()); $errors = $campaign->getErrors(); $this->assertNotEmpty($errors); $this->assertCount(7, $errors); $this->assertArrayHasKey('name', $errors); $this->assertEquals('Name cannot be blank.', $errors['name'][0]); $this->assertArrayHasKey('supportsRichText', $errors); $this->assertEquals('Supports HTML cannot be blank.', $errors['supportsRichText'][0]); $this->assertArrayHasKey('subject', $errors); $this->assertEquals('Subject cannot be blank.', $errors['subject'][0]); $this->assertArrayHasKey('fromName', $errors); $this->assertEquals('From Name cannot be blank.', $errors['fromName'][0]); $this->assertArrayHasKey('fromAddress', $errors); $this->assertEquals('From Address cannot be blank.', $errors['fromAddress'][0]); $this->assertArrayHasKey('textContent', $errors); $this->assertEquals('Please provide at least one of the contents field.', $errors['textContent'][0]); $this->assertArrayHasKey('marketingList', $errors); $this->assertEquals('Marketing List cannot be blank.', $errors['marketingList'][0]); $campaign->name = 'Test Campaign Name2'; $campaign->supportsRichText = 0; $campaign->status = Campaign::STATUS_ACTIVE; $campaign->fromName = 'From Name2'; $campaign->fromAddress = '*****@*****.**'; $campaign->subject = 'Test Subject2'; $campaign->htmlContent = 'Test Html Content2'; $campaign->textContent = 'Test Text Content2'; $campaign->fromName = 'From Name2'; $campaign->fromAddress = '*****@*****.**'; $campaign->marketingList = self::$marketingList; $this->assertTrue($campaign->save()); $id = $campaign->id; unset($campaign); $campaign = Campaign::getById($id); $this->assertEquals('Test Campaign Name2', $campaign->name); $this->assertEquals(0, $campaign->supportsRichText); $this->assertEquals(Campaign::STATUS_ACTIVE, $campaign->status); $this->assertEquals('From Name2', $campaign->fromName); $this->assertEquals('*****@*****.**', $campaign->fromAddress); $this->assertEquals('Test Subject2', $campaign->subject); $this->assertEquals('Test Html Content2', $campaign->htmlContent); $this->assertEquals('Test Text Content2', $campaign->textContent); $this->assertTrue(time() + 15 > DateTimeUtil::convertDbFormatDateTimeToTimestamp($campaign->sendOnDateTime)); }
function add() { if (!$this->checkLogin()) { redirect('admin/campaigns/login'); } $c = new Campaign(); $isErr = 0; $error = ""; if ($this->input->post('savecampaign')) { $c->name = $this->input->post('name'); $c->description = $this->input->post('comment'); $c->countryid = $this->input->post('country'); $c->categoryid = $this->input->post('category'); $c->isInfo = $this->input->post('isinfo'); /* * upload image */ $config['upload_path'] = './uploads/tmp'; $uploadPath = './images/bgs/'; $smallUploadPath = './images/bgsmall/'; $config['allowed_types'] = 'png'; $config['max_size'] = '2048'; $config['max_width'] = '4056'; $config['max_height'] = '3072'; $name = strtolower(str_replace(" ", "_", $c->name)); $c->nickname = $name; $this->load->library('upload', $config); if (!$this->upload->do_upload()) { $error = $error . $this->upload->display_errors('<p>', '</p>'); } else { $tmpImage = $this->upload->data(); // setting the configuration parameters for image manipulations $config1['image_library'] = 'gd2'; $config1['source_image'] = $tmpImage['full_path']; $config1['create_thumb'] = FALSE; $config1['maintain_ratio'] = TRUE; $config1['width'] = 1024; $config1['height'] = 800; $config1['new_image'] = $uploadPath . $name . '.' . $tmpImage['image_type']; $this->load->library('image_lib', $config1); $this->image_lib->resize(); $this->image_lib->clear(); $config2 = $config1; $config2['new_image'] = $smallUploadPath . $name . '.' . $tmpImage['image_type']; $config2['width'] = '100'; $config2['height'] = '80'; $this->load->library('image_lib', $config2); $this->image_lib->resize(); $this->image_lib->clear(); $c->photo = $name . '.' . $tmpImage['image_type']; $c->save(); $isErr = 0; foreach ($c->error->all as $e) { $error = $error . $e . "<br />"; $isErr = 1; } if ($isErr == "0") { $error = "Campaign saved successfully"; } /* * @paragarora: saving tags now for the campaign page */ $tagstr = $this->input->post('tags'); $tags = explode(" ", $tagstr); foreach ($tags as $tag) { $t = new Tag(); $t->name = $tag; $t->save($c); } } } echo "<font color='red'>" . $error . "</font>"; $this->load->view('admin/campaigns/add'); }
public function testSaveAndMarkDeleted() { $campaign = new Campaign(); $campaign->name = 'test'; $campaign->amount = 100; $campaign->save(); //test for record ID to verify that record is saved $this->assertTrue(isset($campaign->id)); $this->assertEquals(36, strlen($campaign->id)); //mark the record as deleted and verify that this record cannot be retrieved anymore. $campaign->mark_deleted($campaign->id); $result = $campaign->retrieve($campaign->id); $this->assertEquals(null, $result); }
/** * Special method to load a campaign with all types of campaignItemActivity */ public function actionLoadCampaignWithAllItemActivityTypes() { if (!Group::isUserASuperAdministrator(Yii::app()->user->userModel)) { throw new NotSupportedException(); } $emailBox = EmailBoxUtil::getDefaultEmailBoxByUser(Yii::app()->user->userModel); $marketingList = new MarketingList(); $marketingList->name = 'Demo Marketing List'; $marketingList->save(); $campaign = new Campaign(); $campaign->marketingList = $marketingList; $campaign->name = 'Campaign with all campaignItemActivity'; $campaign->subject = 'Demo for all types of campaignItemActivities'; $campaign->status = Campaign::STATUS_COMPLETED; $campaign->sendOnDateTime = DateTimeUtil::convertTimestampToDbFormatDateTime(time()); $campaign->supportsRichText = true; $campaign->htmlContent = 'Demo content'; $campaign->fromName = 'Zurmo'; $campaign->fromAddress = '*****@*****.**'; $campaign->enableTracking = true; $saved = $campaign->save(); if (!$saved) { throw new FailedToSaveModelException(); } $contacts = Contact::getAll(); //Awaiting queue $contact = $contacts[0]; $campaignItem = new CampaignItem(); $campaignItem->processed = true; $campaignItem->campaign = $campaign; $campaignItem->contact = $contact; $campaignItem->unrestrictedSave(); //Contact is not subscribed $contact = $contacts[1]; $marketingList->addNewMember($contact->id, true); $campaignItem = new CampaignItem(); $campaignItem->processed = true; $campaignItem->campaign = $campaign; $campaignItem->contact = $contact; $activity = new CampaignItemActivity(); $activity->person = $contact; $activity->campaignItem = $campaignItem; $activity->quantity = 1; $activity->type = CampaignItemActivity::TYPE_SKIP; $activity->save(); $campaignItem->unrestrictedSave(); //Skipped, both primary and secondary are opted out $contact = $contacts[2]; $contact->primaryEmail->emailAddress = $contact->firstName . '*****@*****.**'; $contact->primaryEmail->optOut = true; $contact->secondaryEmail->emailAddress = $contact->firstName . '*****@*****.**'; $contact->secondaryEmail->optOut = true; $contact->save(); $marketingList->addNewMember($contact->id); $campaignItem = new CampaignItem(); $campaignItem->processed = true; $campaignItem->campaign = $campaign; $campaignItem->contact = $contact; $activity = new CampaignItemActivity(); $activity->person = $contact; $activity->campaignItem = $campaignItem; $activity->quantity = 1; $activity->type = CampaignItemActivity::TYPE_SKIP; $activity->save(); $campaignItem->unrestrictedSave(); //Skipped, primary is opted out but secondary is not $contact = $contacts[3]; $contact->primaryEmail->emailAddress = $contact->firstName . '*****@*****.**'; $contact->primaryEmail->optOut = true; $contact->secondaryEmail->emailAddress = $contact->firstName . '*****@*****.**'; $contact->secondaryEmail->optOut = false; $contact->save(); $marketingList->addNewMember($contact->id); $campaignItem = new CampaignItem(); $campaignItem->processed = true; $campaignItem->campaign = $campaign; $campaignItem->contact = $contact; $activity = new CampaignItemActivity(); $activity->person = $contact; $activity->campaignItem = $campaignItem; $activity->quantity = 1; $activity->type = CampaignItemActivity::TYPE_SKIP; $activity->save(); $campaignItem->unrestrictedSave(); //Skipped, primary and secondary not set $contact = $contacts[4]; $contact->primaryEmail = null; $contact->secondaryEmail = null; $contact->save(); $marketingList->addNewMember($contact->id); $campaignItem = new CampaignItem(); $campaignItem->processed = true; $campaignItem->campaign = $campaign; $campaignItem->contact = $contact; $activity = new CampaignItemActivity(); $activity->person = $contact; $activity->campaignItem = $campaignItem; $activity->quantity = 1; $activity->type = CampaignItemActivity::TYPE_SKIP; $activity->save(); $campaignItem->unrestrictedSave(); //Skipped, primary not set but secondary is set $contact = $contacts[5]; $contact->primaryEmail = null; $contact->secondaryEmail->emailAddress = $contact->firstName . '@zurmo.org'; $contact->secondaryEmail->optOut = false; $contact->save(); $marketingList->addNewMember($contact->id); $campaignItem = new CampaignItem(); $campaignItem->processed = true; $campaignItem->campaign = $campaign; $campaignItem->contact = $contact; $activity = new CampaignItemActivity(); $activity->person = $contact; $activity->campaignItem = $campaignItem; $activity->quantity = 1; $activity->type = CampaignItemActivity::TYPE_SKIP; $activity->save(); $campaignItem->unrestrictedSave(); //Queued $contact = $contacts[6]; $campaignItem = new CampaignItem(); $campaignItem->processed = true; $campaignItem->campaign = $campaign; $campaignItem->contact = $contact; $activity = new CampaignItemActivity(); $activity->person = $contact; $activity->campaignItem = $campaignItem; $activity->quantity = 1; $activity->save(); $emailMessage = new EmailMessage(); $emailMessage->setScenario('importModel'); $emailMessage->owner = $contact->owner; $emailMessage->subject = 'Subject'; $emailContent = new EmailMessageContent(); $emailContent->textContent = 'My First Message'; $emailContent->htmlContent = 'Some fake HTML content'; $emailMessage->content = $emailContent; //Sending is current user (super) $sender = new EmailMessageSender(); $sender->fromAddress = '*****@*****.**'; $sender->fromName = 'Zurmo'; $sender->personsOrAccounts->add(Yii::app()->user->userModel); $emailMessage->sender = $sender; //Recipient is BobMessage $recipient = new EmailMessageRecipient(); $recipient->toAddress = '*****@*****.**'; $recipient->toName = strval($contact); $recipient->personsOrAccounts->add($contact); $recipient->type = EmailMessageRecipient::TYPE_TO; $emailMessage->recipients->add($recipient); $emailMessage->folder = EmailFolder::getByBoxAndType($emailBox, EmailFolder::TYPE_OUTBOX); $emailMessage->createdDateTime = DateTimeUtil::convertTimestampToDbFormatDateTime(time()); $emailMessage->save(); if (!$saved) { throw new FailedToSaveModelException(); } $campaignItem->emailMessage = $emailMessage; $campaignItem->unrestrictedSave(); //Queued with error $contact = $contacts[7]; $campaignItem = new CampaignItem(); $campaignItem->processed = true; $campaignItem->campaign = $campaign; $campaignItem->contact = $contact; $activity = new CampaignItemActivity(); $activity->person = $contact; $activity->campaignItem = $campaignItem; $activity->quantity = 1; $activity->save(); $emailMessage = new EmailMessage(); $emailMessage->setScenario('importModel'); $emailMessage->owner = $contact->owner; $emailMessage->subject = 'Subject'; $emailContent = new EmailMessageContent(); $emailContent->textContent = 'My First Message'; $emailContent->htmlContent = 'Some fake HTML content'; $emailMessage->content = $emailContent; //Sending is current user (super) $sender = new EmailMessageSender(); $sender->fromAddress = '*****@*****.**'; $sender->fromName = 'Zurmo'; $sender->personsOrAccounts->add(Yii::app()->user->userModel); $emailMessage->sender = $sender; //Recipient is BobMessage $recipient = new EmailMessageRecipient(); $recipient->toAddress = '*****@*****.**'; $recipient->toName = strval($contact); $recipient->personsOrAccounts->add($contact); $recipient->type = EmailMessageRecipient::TYPE_TO; $emailMessage->recipients->add($recipient); $emailMessage->folder = EmailFolder::getByBoxAndType($emailBox, EmailFolder::TYPE_OUTBOX_ERROR); $emailMessage->createdDateTime = DateTimeUtil::convertTimestampToDbFormatDateTime(time()); $emailMessage->sendAttempts = 2; $emailMessageError = new EmailMessageSendError(); $emailMessageError->serializedData = serialize(array('code' => '0001', 'message' => 'Error Message')); $emailMessage->error = $emailMessageError; $emailMessage->createdDateTime = DateTimeUtil::convertTimestampToDbFormatDateTime(time()); $emailMessage->save(); if (!$saved) { throw new FailedToSaveModelException(); } $campaignItem->emailMessage = $emailMessage; $campaignItem->unrestrictedSave(); //Failure $contact = $contacts[8]; $campaignItem = new CampaignItem(); $campaignItem->processed = true; $campaignItem->campaign = $campaign; $campaignItem->contact = $contact; $activity = new CampaignItemActivity(); $activity->person = $contact; $activity->campaignItem = $campaignItem; $activity->quantity = 1; $activity->save(); $emailMessage = new EmailMessage(); $emailMessage->setScenario('importModel'); $emailMessage->owner = $contact->owner; $emailMessage->subject = 'Subject'; $emailContent = new EmailMessageContent(); $emailContent->textContent = 'My First Message'; $emailContent->htmlContent = 'Some fake HTML content'; $emailMessage->content = $emailContent; //Sending is current user (super) $sender = new EmailMessageSender(); $sender->fromAddress = '*****@*****.**'; $sender->fromName = 'Zurmo'; $sender->personsOrAccounts->add(Yii::app()->user->userModel); $emailMessage->sender = $sender; //Recipient is BobMessage $recipient = new EmailMessageRecipient(); $recipient->toAddress = '*****@*****.**'; $recipient->toName = strval($contact); $recipient->personsOrAccounts->add($contact); $recipient->type = EmailMessageRecipient::TYPE_TO; $emailMessage->recipients->add($recipient); $emailMessage->folder = EmailFolder::getByBoxAndType($emailBox, EmailFolder::TYPE_OUTBOX_FAILURE); $emailMessage->createdDateTime = DateTimeUtil::convertTimestampToDbFormatDateTime(time()); $emailMessage->sendAttempts = 3; $emailMessageError = new EmailMessageSendError(); $emailMessageError->serializedData = serialize(array('code' => '0001', 'message' => 'Error Message')); $emailMessage->error = $emailMessageError; $emailMessage->createdDateTime = DateTimeUtil::convertTimestampToDbFormatDateTime(time()); $emailMessage->save(); if (!$saved) { throw new FailedToSaveModelException(); } $campaignItem->emailMessage = $emailMessage; $campaignItem->unrestrictedSave(); //Sent, open, click, bounce $contact = $contacts[9]; $campaignItem = new CampaignItem(); $campaignItem->processed = true; $campaignItem->campaign = $campaign; $campaignItem->contact = $contact; $activity = new CampaignItemActivity(); $activity->person = $contact; $activity->campaignItem = $campaignItem; $activity->type = CampaignItemActivity::TYPE_CLICK; $activity->quantity = rand(1, 50); $activity->latestDateTime = DateTimeUtil::convertTimestampToDbFormatDateTime(time() + rand(100, 1000)); $activity->latestSourceIP = '10.11.12.13'; $activity->save(); $activity = new CampaignItemActivity(); $activity->person = $contact; $activity->campaignItem = $campaignItem; $activity->type = CampaignItemActivity::TYPE_OPEN; $activity->quantity = rand(1, 50); $activity->latestDateTime = DateTimeUtil::convertTimestampToDbFormatDateTime(time() + rand(100, 1000)); $activity->latestSourceIP = '10.11.12.13'; $activity->save(); $activity = new CampaignItemActivity(); $activity->person = $contact; $activity->campaignItem = $campaignItem; $activity->type = CampaignItemActivity::TYPE_BOUNCE; $activity->quantity = rand(1, 50); $activity->latestDateTime = DateTimeUtil::convertTimestampToDbFormatDateTime(time() + rand(100, 1000)); $activity->latestSourceIP = '10.11.12.13'; $activity->save(); $emailMessage = new EmailMessage(); $emailMessage->setScenario('importModel'); $emailMessage->owner = $contact->owner; $emailMessage->subject = 'Subject'; $emailContent = new EmailMessageContent(); $emailContent->textContent = 'My First Message'; $emailContent->htmlContent = 'Some fake HTML content'; $emailMessage->content = $emailContent; //Sending is current user (super) $sender = new EmailMessageSender(); $sender->fromAddress = '*****@*****.**'; $sender->fromName = 'Zurmo'; $sender->personsOrAccounts->add(Yii::app()->user->userModel); $emailMessage->sender = $sender; //Recipient is BobMessage $recipient = new EmailMessageRecipient(); $recipient->toAddress = '*****@*****.**'; $recipient->toName = strval($contact); $recipient->personsOrAccounts->add($contact); $recipient->type = EmailMessageRecipient::TYPE_TO; $emailMessage->recipients->add($recipient); $emailMessage->folder = EmailFolder::getByBoxAndType($emailBox, EmailFolder::TYPE_SENT); $emailMessage->sentDateTime = DateTimeUtil::convertTimestampToDbFormatDateTime(time()); $emailMessage->save(); if (!$saved) { throw new FailedToSaveModelException(); } $emailMessage->save(); $campaignItem->emailMessage = $emailMessage; $campaignItem->unrestrictedSave(); }