Exemplo n.º 1
0
 /**
  * Execute the action
  */
 public function execute()
 {
     // get parameters
     $this->id = $this->getParameter('mailing_id', 'int');
     // does the item exist
     if (BackendMailmotorModel::existsMailing($this->id)) {
         // call parent, this will probably add some general CSS/JS or other required files
         parent::execute();
         // fetch the mailing
         $mailing = BackendMailmotorModel::getMailing($this->id);
         // get all data for the user we want to edit
         $records = (array) BackendMailmotorCMHelper::getCM()->getCampaignBounces($mailing['cm_id']);
         // reset some data
         if (!empty($records)) {
             // loop the records
             foreach ($records as $record) {
                 // only remove the hard bounces
                 if ($record['bounce_type'] == 'Hard') {
                     // remove the address
                     BackendMailmotorModel::deleteAddresses($record['email']);
                 }
             }
         }
         // trigger event
         BackendModel::triggerEvent($this->getModule(), 'after_delete_bounces');
         // user was deleted, so redirect
         $this->redirect(BackendModel::createURLForAction('statistics') . '&id=' . $mailing['id'] . '&report=deleted-bounces');
     } else {
         $this->redirect(BackendModel::createURLForAction('statistics') . '&error=no-bounces');
     }
 }
 /**
  * Delete addresses
  *
  * @return	void
  */
 private function deleteCustomFields()
 {
     // set the group fields by flipping the custom fields array for this group
     $groupFields = array_flip($this->group['custom_fields']);
     // group custom fields found
     if (!empty($groupFields)) {
         // loop the group fields and empty every value
         foreach ($groupFields as &$field) {
             $field = '';
         }
     }
     // loop the fields
     foreach ($this->fields as $field) {
         // check if the passed field is in the group's field list
         if (isset($groupFields[$field])) {
             // delete the custom field in CM
             BackendMailmotorCMHelper::deleteCustomField('[' . $field . ']', $this->group['id']);
             // remove the field from the group's field listing
             unset($groupFields[$field]);
         }
     }
     // update custom fields for this group
     BackendMailmotorModel::updateCustomFields($groupFields, $this->group['id']);
     // redirect
     $this->redirect(BackendModel::createURLForAction('custom_fields') . '&group_id=' . $this->group['id'] . '&report=deleted-custom-fields&var=' . $this->group['name']);
 }
Exemplo n.º 3
0
 /**
  * Validate the form
  */
 private function validateForm()
 {
     // is the form submitted?
     if ($this->frm->isSubmitted()) {
         // cleanup the submitted fields, ignore fields that were added by hackers
         $this->frm->cleanupFields();
         // shorten fields
         $txtName = $this->frm->getField('name');
         $rbtDefaultForLanguage = $this->frm->getField('default');
         // validate fields
         if ($txtName->isFilled(BL::err('NameIsRequired'))) {
             // check if the group exists by name
             if (BackendMailmotorModel::existsGroupByName($txtName->getValue())) {
                 $txtName->addError(BL::err('GroupAlreadyExists'));
             }
         }
         // no errors?
         if ($this->frm->isCorrect()) {
             // build item
             $item['name'] = $txtName->getValue();
             $item['created_on'] = BackendModel::getUTCDate('Y-m-d H:i:s');
             $item['language'] = $rbtDefaultForLanguage->getValue() === '0' ? null : $rbtDefaultForLanguage->getValue();
             $item['is_default'] = $rbtDefaultForLanguage->getChecked() ? 'Y' : 'N';
             // insert the item
             $item['id'] = BackendMailmotorCMHelper::insertGroup($item);
             // check if all default groups were set
             BackendMailmotorModel::checkDefaultGroups();
             // trigger event
             BackendModel::triggerEvent($this->getModule(), 'after_add_group', array('item' => $item));
             // everything is saved, so redirect to the overview
             $this->redirect(BackendModel::createURLForAction('groups') . '&report=added&var=' . urlencode($item['name']) . '&highlight=id-' . $item['id']);
         }
     }
 }
Exemplo n.º 4
0
 /**
  * Execute the action
  */
 public function execute()
 {
     parent::execute();
     // get parameters
     $clientId = SpoonFilter::getPostValue('client_id', null, '');
     // check input
     if (empty($clientId)) {
         $this->output(self::BAD_REQUEST);
     }
     // get basic details for this client
     $client = BackendMailmotorCMHelper::getCM()->getClient($clientId);
     // CM was successfully initialized
     $this->output(self::OK, $client);
 }
Exemplo n.º 5
0
 /**
  * Execute the action
  *
  * @return	void
  */
 public function execute()
 {
     // call parent, this will probably add some general CSS/JS or other required files
     parent::execute();
     // get parameters
     $clientId = SpoonFilter::getPostValue('client_id', null, '');
     // check input
     if (empty($clientId)) {
         $this->output(self::BAD_REQUEST);
     }
     // get basic details for this client
     $client = BackendMailmotorCMHelper::getCM()->getClient($clientId);
     // CM was successfully initialized
     $this->output(self::OK, $client);
 }
Exemplo n.º 6
0
 /**
  * Gets all data needed for this page
  */
 private function getData()
 {
     $this->id = $this->getParameter('id', 'int');
     // does the item exist
     if (!BackendMailmotorModel::existsMailing($this->id)) {
         $this->redirect(BackendModel::createURLForAction('index') . '&error=mailing-does-not-exist');
     }
     // get mailing
     $this->mailing = BackendMailmotorModel::getMailing($this->id);
     // fetch the statistics
     $this->statistics = BackendMailmotorCMHelper::getStatistics($this->id, true);
     // no stats found
     if ($this->statistics === false) {
         $this->redirect(BackendModel::createURLForAction('index') . '&error=no-statistics-loaded&var=' . str_replace('#', '', $this->mailing['name']));
     }
 }
Exemplo n.º 7
0
 /**
  * Gets all data needed for this page
  */
 private function getData()
 {
     // get parameters
     $id = $this->getParameter('mailing_id', 'int');
     // does the item exist
     if (!BackendMailmotorModel::existsMailing($id)) {
         $this->redirect(BackendModel::createURLForAction('index') . '&error=mailing-does-not-exist');
     }
     // fetch the mailing
     $this->mailing = BackendMailmotorModel::getMailing($id);
     // fetch the bounces
     $this->bounces = BackendMailmotorCMHelper::getBounces($this->mailing['id']);
     // does the item exist
     if (empty($this->bounces)) {
         $this->redirect(BackendModel::createURLForAction('statistics') . '&id=' . $this->mailing['id'] . '&error=no-bounces');
     }
 }
 /**
  * Gets all data needed for this page
  *
  * @return	void
  */
 private function getData()
 {
     // get parameters
     $this->id = $this->getParameter('id', 'int');
     // does the item exist
     if (!BackendMailmotorModel::existsCampaign($this->id)) {
         $this->redirect(BackendModel::createURLForAction('campaigns') . '&error=campaign-does-not-exist');
     }
     // store mailing
     $this->campaign = BackendMailmotorModel::getCampaign($this->id);
     // fetch the statistics
     $this->statistics = BackendMailmotorCMHelper::getStatisticsByCampaignID($this->id, true);
     // no stats found
     if ($this->statistics === false || empty($this->statistics)) {
         $this->redirect(BackendModel::createURLForAction('campaigns') . '&error=no-statistics-loaded');
     }
 }
Exemplo n.º 9
0
 /**
  * Execute the action
  */
 public function execute()
 {
     parent::execute();
     // get parameters
     $id = SpoonFilter::getPostValue('id', null, '', 'int');
     // validate
     if ($id == '' || !BackendMailmotorModel::existsMailing($id)) {
         $this->output(self::BAD_REQUEST, null, 'No mailing found.');
     }
     // get mailing record
     $mailing = BackendMailmotorModel::getMailing($id);
     /*
     	mailing was already sent
     	We use a custom status code 900 because we want to do more with JS than triggering an error
     */
     if ($mailing['status'] == 'sent') {
         $this->output(900, null, BL::err('MailingAlreadySent', $this->getModule()));
     }
     // make a regular date out of the send_on timestamp
     $mailing['delivery_date'] = date('Y-m-d H:i:s', $mailing['send_on']);
     // send the mailing
     try {
         // only update the mailing if it was queued
         if ($mailing['status'] == 'queued') {
             BackendMailmotorCMHelper::updateMailing($mailing);
         } else {
             BackendMailmotorCMHelper::sendMailing($mailing);
         }
     } catch (Exception $e) {
         // stop the script and show our error
         $this->output(902, null, $e->getMessage());
     }
     // set status to 'sent'
     $item['id'] = $id;
     $item['status'] = $mailing['send_on'] > time() ? 'queued' : 'sent';
     // update the mailing record
     BackendMailmotorModel::updateMailing($item);
     // trigger event
     BackendModel::triggerEvent($this->getModule(), 'after_mailing_status_' . $item['status'], array('item' => $item));
     // we made it \o/
     $this->output(self::OK, array('mailing_id' => $item['id']), BL::msg('MailingSent', $this->getModule()));
 }
Exemplo n.º 10
0
 /**
  * Execute the action
  */
 public function execute()
 {
     parent::execute();
     // action to execute
     $action = SpoonFilter::getGetValue('action', array('delete'), 'delete');
     // no id's provided
     if (!isset($_GET['id'])) {
         $this->redirect(BackendModel::createURLForAction('groups') . '&error=no-selection');
     } else {
         // redefine id's
         $ids = (array) $_GET['id'];
         // delete comment(s)
         if ($action == 'delete') {
             BackendMailmotorCMHelper::deleteGroups($ids);
             // trigger event
             BackendModel::triggerEvent($this->getModule(), 'after_delete_groups', array('ids' => $ids));
         }
     }
     // redirect
     $this->redirect(BackendModel::createURLForAction('groups') . '&report=delete-groups');
 }
Exemplo n.º 11
0
 /**
  * Validate the form
  */
 private function validateForm()
 {
     // is the form submitted?
     if ($this->frm->isSubmitted()) {
         // cleanup the submitted fields, ignore fields that were added by hackers
         $this->frm->cleanupFields();
         // validate fields
         $this->frm->getField('email')->isFilled(BL::err('EmailIsRequired'));
         // get addresses
         $addresses = (array) explode(',', $this->frm->getField('email')->getValue());
         // loop addresses
         foreach ($addresses as $email) {
             // validate email
             if (!SpoonFilter::isEmail(trim($email))) {
                 // add error if needed
                 $this->frm->getField('email')->addError(BL::err('ContainsInvalidEmail'));
                 // stop looking
                 break;
             }
         }
         $this->frm->getField('groups')->isFilled(BL::err('ChooseAtLeastOneGroup'));
         // no errors?
         if ($this->frm->isCorrect()) {
             // build item
             $item = $this->frm->getValues();
             $item['source'] = BL::lbl('Manual');
             $item['created_on'] = BackendModel::getUTCDate('Y-m-d H:i:s');
             // loop the groups
             foreach ($item['groups'] as $group) {
                 foreach ($addresses as $email) {
                     BackendMailmotorCMHelper::subscribe(trim($email), $group);
                 }
             }
             // trigger event
             BackendModel::triggerEvent($this->getModule(), 'after_add_address', array('item' => $item));
             // everything is saved, so redirect to the overview
             $this->redirect(BackendModel::createURLForAction('addresses') . (!empty($this->groupId) ? '&group_id=' . $this->groupId : '') . '&report=added');
         }
     }
 }
Exemplo n.º 12
0
 /**
  * Execute the action
  *
  * @return	void
  */
 public function execute()
 {
     // call parent, this will probably add some general CSS/JS or other required files
     parent::execute();
     // action to execute
     $action = SpoonFilter::getGetValue('action', array('delete'), 'delete');
     // no id's provided
     if (!isset($_GET['id'])) {
         $this->redirect(BackendModel::createURLForAction('index') . '&error=no-items-selected');
     } else {
         // redefine id's
         $ids = (array) $_GET['id'];
         // delete comment(s)
         if ($action == 'delete') {
             BackendMailmotorCMHelper::deleteMailings($ids);
             // trigger event
             BackendModel::triggerEvent($this->getModule(), 'after_delete_mailings', array('ids' => $ids));
         }
     }
     // redirect
     $this->redirect(BackendModel::createURLForAction('index') . '&report=delete_mailings');
 }
Exemplo n.º 13
0
 /**
  * Delete addresses
  */
 private function deleteAddresses()
 {
     // no group set
     if ($this->groupId == '') {
         $this->groupId = null;
     }
     // get all groups
     $groupIds = BackendMailmotorModel::getGroupIDs();
     // loop the emails
     foreach ($this->emails as $email) {
         // the group ID is not set
         if ($this->groupId == null) {
             // if no groups were set, break here
             if (empty($groupIds)) {
                 break;
             }
             // loop the group IDs
             foreach ($groupIds as $groupId) {
                 // try to unsubscribe this address
                 try {
                     BackendMailmotorCMHelper::unsubscribe($email, $groupId);
                 } catch (Exception $e) {
                     // do nothing
                 }
             }
             // delete all addresses
             BackendMailmotorModel::deleteAddresses($email);
         } else {
             BackendMailmotorCMHelper::unsubscribe($email, $this->groupId);
         }
     }
     // trigger event
     BackendModel::triggerEvent($this->getModule(), 'after_delete_addresses');
     // redirect
     $this->redirect(BackendModel::createURLForAction('addresses') . '&report=delete-addresses' . (!empty($this->groupId) ? '&group_id=' . $this->groupId : ''));
 }
Exemplo n.º 14
0
 /**
  * Load the datagrid for statistics
  *
  * @return	void
  */
 private function loadStatistics()
 {
     // fetch the latest mailing
     $mailing = BackendMailmotorModel::getSentMailings(1);
     // check if a mailing was found
     if (empty($mailing)) {
         return false;
     }
     // check if a mailing was set
     if (!isset($mailing[0])) {
         return false;
     }
     // show the sent mailings block
     $this->tpl->assign('oSentMailings', true);
     // require the helper class
     require_once BACKEND_MODULES_PATH . '/mailmotor/engine/helper.php';
     // fetch the statistics for this mailing
     $stats = BackendMailmotorCMHelper::getStatistics($mailing[0]['id'], true);
     // reformat the send date
     $mailing[0]['sent'] = SpoonDate::getDate('d-m-Y', $mailing[0]['sent']) . ' ' . BL::lbl('At') . ' ' . SpoonDate::getDate('H:i', $mailing);
     // get results
     $results[] = array('label' => BL::lbl('MailmotorLatestMailing'), 'value' => $mailing[0]['name']);
     $results[] = array('label' => BL::lbl('MailmotorSendDate'), 'value' => $mailing[0]['sent']);
     $results[] = array('label' => BL::lbl('MailmotorSent'), 'value' => $stats['recipients'] . ' (' . $stats['recipients_percentage'] . ')');
     $results[] = array('label' => BL::lbl('MailmotorOpened'), 'value' => $stats['unique_opens'] . ' (' . $stats['unique_opens_percentage'] . ')');
     $results[] = array('label' => BL::lbl('MailmotorClicks'), 'value' => $stats['clicks_total'] . ' (' . $stats['clicks_percentage'] . ')');
     // there are some results
     if (!empty($results)) {
         // get the datagrid
         $dataGrid = new BackendDataGridArray($results);
         // no pagination
         $dataGrid->setPaging(false);
         // parse the datagrid
         $this->tpl->assign('dgMailmotorStatistics', $dataGrid->getContent());
     }
 }
Exemplo n.º 15
0
    /**
     * Get all data for a given mailing
     *
     * @param int $id The id of the mailing.
     * @return array
     */
    public static function getMailing($id)
    {
        // get record and return it
        $record = (array) BackendModel::getDB()->getRecord('SELECT mm.*, UNIX_TIMESTAMP(mm.send_on) AS send_on
			 FROM mailmotor_mailings AS mm
			 WHERE mm.id = ?', array((int) $id));
        // stop here if record is empty
        if (empty($record)) {
            return array();
        }
        // get groups for this mailing ID
        $record['groups'] = self::getGroupIDsByMailingID($id);
        $record['recipients'] = self::getAddressesByGroupID($record['groups']);
        // fetch CM id for this mailing
        $record['cm_id'] = BackendMailmotorCMHelper::getCampaignMonitorID('campaign', $record['id']);
        // return the record
        return $record;
    }
Exemplo n.º 16
0
 /**
  * Processes the subscriber import. Returns an array with failed subscribers.
  *
  * @return	array			A list with failed subscribers.
  * @param	array $csv		The uploaded CSV file.
  * @param	int $groupID	The group ID for which we're importing.
  */
 private function processImport($csv, $groupID)
 {
     // the CM list ID for the given group ID
     $listID = BackendMailmotorCMHelper::getCampaignMonitorID('list', $groupID);
     // reserve variables
     $subscribers = array();
     /*
     	IMPORTANT NOTE: CM only allows a maximum amount of 100 subscribers for each import. So we have to batch
     */
     foreach ($csv as $key => $record) {
         // no e-mail address set means stop here
         if (empty($record['email'])) {
             continue;
         }
         // build record to insert
         $subscribers[$key] = $this->formatSubscriberCSVRow($record);
     }
     // divide the subscribers into batches of 100
     $batches = array_chunk($subscribers, 100);
     $failed = array();
     $feedback = array();
     $failedSubscribersCSV = array();
     // loop the batches
     foreach ($batches as $key => $batch) {
         // import every 100 subscribers
         $feedback[$key] = BackendMailmotorCMHelper::getCM()->importSubscribers($batch, $listID);
         // if the batch did not contain failed imports, we continue looping
         if (empty($feedback[$key])) {
             continue;
         }
         // merge the feedback results with the full failed set
         $failed = array_merge($failed, $feedback[$key]);
     }
     // now we have to loop all uploaded CSV rows in order to provide a .csv with all failed records.
     foreach ($csv as $row) {
         // the subscriber didn't fail the import, so we proceed to insert him in our database
         if (!in_array($row['email'], $failed)) {
             // build subscriber record
             $subscriber = array();
             $subscriber['email'] = $row['email'];
             $subscriber['source'] = 'import';
             $subscriber['created_on'] = BackendModel::getUTCDate();
             $subscriber['groups'] = $groupID;
             // unset the email (for the custom fields)
             unset($row['email']);
             // save the address in our database, with the assigned custom fields
             BackendMailmotorModel::saveAddress($subscriber, $groupID, $row);
             // continue looping
             continue;
         }
         // subscriber failed in import, so add his record to the fail-csv
         $failedSubscribersCSV[] = $row;
     }
     // return the failed subscribers
     return $failedSubscribersCSV;
 }
Exemplo n.º 17
0
 /**
  * Returns the statistics for a given mailing
  *
  * @param int $id The id of the mailing.
  * @param bool[optional] $fetchClicks If the click-count should be included.
  * @param bool[optional] $fetchOpens If the open-count should be included.
  * @return array
  */
 public static function getStatistics($id, $fetchClicks = false, $fetchOpens = false)
 {
     // check if the mailing exists
     if (!BackendMailmotorModel::existsMailing($id)) {
         throw new SpoonException('No mailing found for id ' . $id);
     }
     // fetch cmID
     $cmId = self::getCampaignMonitorID('campaign', $id);
     // fetch the CM ID
     if ($cmId) {
         // fetch the statistics
         $stats = self::getCM()->getCampaignSummary($cmId);
         // stop here if no recipients were found
         if ($stats['recipients'] == 0) {
             return false;
         }
         // reset the bounces to match the real ones
         $bounces = BackendMailmotorCMHelper::getBounces($id);
         // re-calculate base stats to match CM's
         $stats['bounces'] = count($bounces);
         $stats['recipients'] = $stats['recipients'];
         $stats['recipients_total'] = $stats['recipients'];
         $stats['unopens'] = $stats['recipients'] - $stats['unique_opens'] - $stats['bounces'];
         $stats['clicks_total'] = 0;
         // add percentages to these stats
         $stats['bounces_percentage'] = $stats['recipients'] == 0 ? 0 : floor($stats['bounces'] / $stats['recipients_total'] * 100) . '%';
         $stats['recipients_percentage'] = $stats['recipients'] == 0 ? 0 : ceil($stats['recipients'] / $stats['recipients_total'] * 100) . '%';
         $stats['unique_opens_percentage'] = $stats['recipients'] == 0 ? 0 : ceil($stats['unique_opens'] / $stats['recipients'] * 100) . '%';
         $stats['unopens_percentage'] = $stats['recipients'] == 0 ? 0 : floor($stats['unopens'] / $stats['recipients'] * 100) . '%';
         $stats['clicks_percentage'] = $stats['recipients'] == 0 ? 0 : ceil($stats['clicks'] / $stats['recipients'] * 100) . '%';
         // fetch clicks or not?
         if ($fetchClicks) {
             // get detailed click reports
             $subscriberClicks = self::getCM()->getCampaignClicks($cmId);
             // links have been clicked
             if (!empty($subscriberClicks)) {
                 // declare array
                 $stats['clicked_links'] = array();
                 $stats['clicked_links_by'] = $subscriberClicks;
                 // filter out the clicked links
                 foreach ($subscriberClicks as $link => $clickers) {
                     // count the clickers
                     $clickerCount = count($clickers);
                     $stats['clicked_links'][] = array('link' => $link, 'clicks' => $clickerCount);
                     $stats['clicks_total'] += $clickerCount;
                 }
                 /*
                 // re-loop so we can fix the keys
                 foreach($stats['clicked_links'] as $link)
                 {
                 	// store the link data
                 	$stats['clicked_links'][] = array('link' => urlencode($link['link']));
                 
                 	// unset the record with the link as key
                 	unset($stats['clicked_links'][$link['link']]);
                 }
                 
                 // re-loop so we can fix the keys
                 foreach($stats['clicked_links_by'] as $link => $clicks)
                 {
                 	// loop the clicks
                 	foreach($clicks as $click)
                 	{
                 		// store the link data
                 		$stats['clicked_links_by'][$link][] = array('email' => $click['email']);
                 
                 		// unset the record with the link as key
                 		unset($stats['clicked_links_by'][$link][$click['email']]);
                 	}
                 }
                 */
             }
         }
         // fetch opened stats or not?
         if ($fetchOpens) {
             // fetch opens
             $stats['opens'] = self::getMailingOpens($cmId);
         }
         // return the results
         return $stats;
     }
     // at this point, return false
     return false;
 }
Exemplo n.º 18
0
 /**
  * Updates a client record.
  *
  * @return	mixed
  * @param	array $record		The client record to update.
  */
 private function updateClient($record)
 {
     // get the account settings
     $url = BackendModel::getModuleSetting($this->getModule(), 'cm_url');
     $username = BackendModel::getModuleSetting($this->getModule(), 'cm_username');
     $password = BackendModel::getModuleSetting($this->getModule(), 'cm_password');
     // try and update the client info
     try {
         // fetch complete list of timezones as pairs
         $timezones = BackendMailmotorCMHelper::getTimezonesAsPairs();
         // init CampaignMonitor object
         $cm = new CampaignMonitor($url, $username, $password, 10, $this->clientID);
         // update the client
         $cm->updateClientBasics($record['company_name'], $record['contact_name'], $record['contact_email'], $record['country'], $timezones[$record['timezone']]);
     } catch (Exception $e) {
         // add an error to the email field
         $this->redirect(BackendModel::createURLForAction('settings') . '&error=campaign-monitor-error&var=' . $e->getMessage() . '#tabSettingsClient');
     }
 }
Exemplo n.º 19
0
 /**
  * Checks if any groups are made yet. Depending on the client that is linked to Fork, it will creates default groups if none were found in CampaignMonitor.
  * If they were, the user is presented with an overview to import all groups and their subscribers in Fork.
  *
  * @return	void
  */
 private function checkForGroups()
 {
     // groups are already set
     if (BackendModel::getModuleSetting('mailmotor', 'cm_groups_set')) {
         return false;
     }
     // no CM data found
     if (!BackendMailmotorCMHelper::checkAccount()) {
         return false;
     }
     // check if there are external groups present in CampaignMonitor
     if ($this->checkForExternalGroups()) {
         // external groups were found, so redirect to the import_groups action
         SpoonHTTP::redirect(BackendModel::createURLForAction('import_groups', 'mailmotor'));
     }
     // fetch the default groups, language abbreviation is the array key
     $groups = BackendMailmotorModel::getDefaultGroups();
     // loop languages
     foreach (BL::getActiveLanguages() as $language) {
         // this language does not have a default group set
         if (!isset($groups[$language])) {
             // set group record
             $group['name'] = 'Website (' . strtoupper($language) . ')';
             $group['language'] = $language;
             $group['is_default'] = 'Y';
             $group['created_on'] = date('Y-m-d H:i:s');
             try {
                 // insert the group in CampaignMonitor
                 BackendMailmotorCMHelper::insertGroup($group);
             } catch (CampaignMonitorException $e) {
                 // ignore
             }
         }
     }
     // we have groups set, and default groups chosen
     BackendModel::setModuleSetting('mailmotor', 'cm_groups_set', true);
     BackendModel::setModuleSetting('mailmotor', 'cm_groups_defaults_set', true);
 }
Exemplo n.º 20
0
 /**
  * Execute the action
  *
  * @return	void
  */
 public function execute()
 {
     // call parent, this will probably add some general CSS/JS or other required files
     parent::execute();
     // get parameters
     $id = SpoonFilter::getPostValue('id', null, '', 'int');
     // validate
     if ($id == '' || !BackendMailmotorModel::existsMailing($id)) {
         $this->output(self::BAD_REQUEST, null, 'No mailing found.');
     }
     // get mailing record
     $mailing = BackendMailmotorModel::getMailing($id);
     /*
     	mailing was already sent
     	We use a custom status code 900 because we want to do more with JS than triggering an error
     */
     if ($mailing['status'] == 'sent') {
         $this->output(900, null, BL::err('MailingAlreadySent', $this->getModule()));
     }
     // make a regular date out of the send_on timestamp
     $mailing['delivery_date'] = date('Y-m-d H:i:s', $mailing['send_on']);
     // send the mailing
     try {
         // only update the mailing if it was queued
         if ($mailing['status'] == 'queued') {
             BackendMailmotorCMHelper::updateMailing($mailing);
         } else {
             BackendMailmotorCMHelper::sendMailing($mailing);
         }
     } catch (Exception $e) {
         // fetch campaign ID in CM
         $cmId = BackendMailmotorCMHelper::getCampaignMonitorID('campaign', $id);
         // check if the CM ID isn't false
         if ($cmId !== false) {
             // delete the mailing in CM
             BackendMailmotorCMHelper::getCM()->deleteCampaign($cmId);
             // delete the reference
             BackendModel::getDB(true)->delete('mailmotor_campaignmonitor_ids', 'cm_id = ?', $cmId);
         }
         // check what error we have
         switch ($e->getMessage()) {
             case 'HTML Content URL Required':
                 $message = BL::err('HTMLContentURLRequired', $this->getModule());
                 break;
             case 'Payment details required':
                 $message = sprintf(BL::err('PaymentDetailsRequired', $this->getModule()), BackendModel::getModuleSetting($this->getModule(), 'cm_username'));
                 break;
             case 'Duplicate Campaign Name':
                 $message = BL::err('DuplicateCampaignName', $this->getModule());
                 break;
             default:
                 $message = $e->getMessage();
                 break;
         }
         // stop the script and show our error
         $this->output(902, null, $message);
     }
     // set status to 'sent'
     $item['id'] = $id;
     $item['status'] = $mailing['send_on'] > time() ? 'queued' : 'sent';
     // update the mailing record
     BackendMailmotorModel::updateMailing($item);
     // trigger event
     BackendModel::triggerEvent($this->getModule(), 'after_mailing_status_' . $item['status'], array('item' => $item));
     // we made it \o/
     $this->output(self::OK, array('mailing_id' => $item['id']), BL::msg('MailingSent', $this->getModule()));
 }
Exemplo n.º 21
0
 /**
  * Execute the action
  */
 public function execute()
 {
     parent::execute();
     // get parameters
     $mailingId = SpoonFilter::getPostValue('mailing_id', null, '', 'int');
     $subject = SpoonFilter::getPostValue('subject', null, '');
     $contentHTML = urldecode(SpoonFilter::getPostValue('content_html', null, ''));
     $contentPlain = SpoonFilter::getPostValue('content_plain', null, '');
     // validate mailing ID
     if ($mailingId == '') {
         $this->output(self::BAD_REQUEST, null, 'No mailing ID provided');
     }
     // get mailing record
     $this->mailing = BackendMailmotorModel::getMailing($mailingId);
     // record is empty
     if (empty($this->mailing)) {
         $this->output(self::BAD_REQUEST, null, BL::err('MailingDoesNotExist', $this->getModule()));
     }
     // validate other fields
     if ($subject == '') {
         $this->output(900, array('element' => 'subject', 'element_error' => BL::err('NoSubject', $this->getModule())), BL::err('FormError'));
     }
     // set plain content
     $contentPlain = empty($contentPlain) ? SpoonFilter::stripHTML($contentHTML) : $contentPlain;
     // add unsubscribe link
     if (mb_strpos($contentPlain, '[unsubscribe]') === false) {
         $contentPlain .= PHP_EOL . '[unsubscribe]';
     }
     // build data
     $item['id'] = $this->mailing['id'];
     $item['subject'] = $subject;
     $item['content_plain'] = $contentPlain;
     $item['content_html'] = $contentHTML;
     $item['edited_on'] = date('Y-m-d H:i:s');
     // update mailing in our database
     BackendMailmotorModel::updateMailing($item);
     /*
     	we should insert the draft into campaignmonitor here,
     	so we can use sendCampaignPreview in step 4.
     */
     $item['groups'] = $this->mailing['groups'];
     $item['name'] = $this->mailing['name'];
     $item['from_name'] = $this->mailing['from_name'];
     $item['from_email'] = $this->mailing['from_email'];
     $item['reply_to_email'] = $this->mailing['reply_to_email'];
     try {
         BackendMailmotorCMHelper::saveMailingDraft($item);
     } catch (Exception $e) {
         // CM did not receive a valid URL
         if (strpos($e->getMessage(), 'HTML Content URL Required')) {
             $message = BL::err('HTMLContentURLRequired', $this->getModule());
         } elseif (strpos($e->getMessage(), 'Payment details required')) {
             $error = BL::err('PaymentDetailsRequired', $this->getModule());
             $cmUsername = BackendModel::getModuleSetting($this->getModule(), 'cm_username');
             $message = sprintf($error, $cmUsername);
         } elseif (strpos($e->getMessage(), 'Duplicate Campaign Name')) {
             $message = BL::err('DuplicateCampaignName', $this->getModule());
         } else {
             $message = $e->getMessage();
         }
         // stop the script and show our error
         $this->output(902, null, $message);
     }
     // trigger event
     BackendModel::triggerEvent($this->getModule(), 'after_edit_mailing_step3', array('item' => $item));
     // output
     $this->output(self::OK, array('mailing_id' => $mailingId), BL::msg('MailingEdited', $this->getModule()));
 }
Exemplo n.º 22
0
 /**
  * Validate the form
  */
 private function validateForm()
 {
     // is the form submitted?
     if ($this->frm->isSubmitted()) {
         // cleanup the submitted fields, ignore fields that were added by hackers
         $this->frm->cleanupFields();
         // shorten fields
         $txtGroup = $this->frm->getField('group');
         // validate fields
         if ($txtGroup->isFilled(BL::err('NameIsRequired'))) {
             if (BackendMailmotorModel::existsGroupByName($txtGroup->getValue())) {
                 $txtGroup->addError(BL::err('GroupAlreadyExists'));
             }
         }
         // no errors?
         if ($this->frm->isCorrect()) {
             // build item
             $item['name'] = $txtGroup->getValue();
             $item['created_on'] = BackendModel::getUTCDate('Y-m-d H:i:s');
             // update the item
             $item['id'] = BackendMailmotorCMHelper::insertGroup($item);
             // loop the adresses
             foreach ($this->statistics['clicked_links_by'][$this->linkURL] as $clicker) {
                 // subscribe the user to the created group
                 BackendMailmotorCMHelper::subscribe($clicker['email'], $item['id']);
             }
             // everything is saved, so redirect to the overview
             $this->redirect(BackendModel::createURLForAction('statistics_link') . '&url=' . $this->linkURL . '&mailing_id=' . $this->mailing['id'] . '&report=group-added&var=' . urlencode($item['name']) . '&highlight=id-' . $this->mailing['id']);
         }
     }
 }
Exemplo n.º 23
0
 /**
  * Validate the form
  */
 private function validateForm()
 {
     // is the form submitted?
     if ($this->frm->isSubmitted()) {
         // cleanup the submitted fields, ignore fields that were added by hackers
         $this->frm->cleanupFields();
         // shorten fields
         $txtName = $this->frm->getField('name');
         // validate fields
         if ($txtName->isFilled(BL::err('NameIsRequired'))) {
             if (in_array($txtName->getValue(), $this->group['custom_fields'])) {
                 $txtName->addError(BL::err('CustomFieldExists'));
             }
         }
         // no errors?
         if ($this->frm->isCorrect()) {
             try {
                 // add the new item to the custom fields list
                 $this->group['custom_fields'][] = $txtName->getValue();
                 // set the group fields by flipping the custom fields array for this group
                 $groupFields = array_flip($this->group['custom_fields']);
                 // group custom fields found
                 if (!empty($groupFields)) {
                     // loop the group fields and empty every value
                     foreach ($groupFields as &$field) {
                         $field = '';
                     }
                 }
                 // addresses found and custom field delete with CM
                 BackendMailmotorCMHelper::createCustomField($txtName->getValue(), $this->group['id']);
                 // update custom fields for this group
                 BackendMailmotorModel::updateCustomFields($groupFields, $this->group['id']);
             } catch (Exception $e) {
                 // redirect with a custom error
                 $this->redirect(BackendModel::createURLForAction('custom_fields') . '&group_id=' . $this->group['id'] . '&error=campaign-monitor-error&var=' . urlencode($e->getMessage()));
             }
             // everything is saved, so redirect to the overview
             $this->redirect(BackendModel::createURLForAction('custom_fields') . '&group_id=' . $this->group['id'] . '&report=added&var=' . urlencode($txtName->getValue()) . '&highlight=id-' . $this->group['id']);
         }
     }
 }
Exemplo n.º 24
0
 /**
  * Validate the form for step 4
  */
 private function validateFormForStep4()
 {
     // is the form submitted?
     if ($this->frm->isSubmitted()) {
         // cleanup the submitted fields, ignore fields that were added by hackers
         $this->frm->cleanupFields();
         // shorten fields
         $txtEmail = $this->frm->getField('email');
         $txtSendOnDate = $this->frm->getField('send_on_date');
         $txtSendOnTime = $this->frm->getField('send_on_time');
         // validation
         if ($txtEmail->isFilled(BL::err('FieldIsRequired'))) {
             $txtEmail->isEmail(BL::err('EmailIsInvalid'));
         }
         $txtSendOnDate->isValid(BL::err('DateIsInvalid'));
         $txtSendOnTime->isValid(BL::err('TimeIsInvalid'));
         // no errors?
         if ($this->frm->isCorrect()) {
             /*
             	the actual sending of a mailing happens in ajax/send_mailing.php
             	This, however, is the point where a preview is sent to a specific address.
             */
             BackendMailmotorCMHelper::sendPreviewMailing($this->id, $txtEmail->getValue());
             // build URL
             $url = BackendModel::createURLForAction('edit') . '&id=' . $this->id . '&step=4';
             // send the preview
             $this->redirect($url . '&report=preview-sent&var=' . $txtEmail->getValue());
         }
     }
 }
Exemplo n.º 25
0
 /**
  * Validate the form
  *
  * @return	void
  */
 private function validateForm()
 {
     // is the form submitted?
     if ($this->frm->isSubmitted()) {
         // cleanup the submitted fields, ignore fields that were added by hackers
         $this->frm->cleanupFields();
         // no errors?
         if ($this->frm->isCorrect()) {
             // the total amount of subscribers
             $subscribersTotal = 0;
             // loop all groups
             foreach ($this->externalGroups as $group) {
                 // insert them in our database
                 $groupID = BackendModel::getDB(true)->insert('mailmotor_groups', array('name' => $group['name'], 'custom_fields' => $group['custom_fields'], 'created_on' => BackendModel::getUTCDate()));
                 // insert the CM ID
                 BackendMailmotorCMHelper::insertCampaignMonitorID('list', $group['id'], $groupID);
                 // continue looping if this group has no subscribers
                 if (empty($group['subscribers'])) {
                     continue;
                 }
                 // add this groups subscribers amount to the total
                 $subscribersTotal += $group['subscribers_amount'];
                 // loop the subscribers for this group, and import them
                 foreach ($group['subscribers'] as $subscriber) {
                     // build new subscriber record
                     $item = array();
                     $item['email'] = $subscriber['email'];
                     $item['source'] = 'import';
                     $item['created_on'] = $subscriber['date'];
                     // add an additional custom field 'name', if it was set in the subscriber record
                     if (!empty($subscriber['name'])) {
                         $subscriber['custom_fields']['Name'] = $subscriber['name'];
                     }
                     // save the subscriber in our database, and subscribe it to this group
                     BackendMailmotorModel::saveAddress($item, $groupID, !empty($subscriber['custom_fields']) ? $subscriber['custom_fields'] : null);
                 }
             }
             // at this point, groups are set
             BackendModel::setModuleSetting($this->getModule(), 'cm_groups_set', true);
             // trigger event
             BackendModel::triggerEvent($this->getModule(), 'after_import_groups');
             // redirect to the index
             $this->redirect(BackendModel::createURLForAction('index', $this->getModule()) . '&report=groups-imported&var[]=' . count($this->externalGroups) . '&var[]=' . $subscribersTotal);
         }
     }
 }
Exemplo n.º 26
0
 /**
  * Validate the form
  */
 private function validateForm()
 {
     // is the form submitted?
     if ($this->frm->isSubmitted()) {
         // cleanup the submitted fields, ignore fields that were added by hackers
         $this->frm->cleanupFields();
         // get subscriptions
         if (!empty($this->subscriptions)) {
             $ddmGroups = $this->frm->getField('subscriptions');
         }
         // no errors?
         if ($this->frm->isCorrect()) {
             // build item
             $item['email'] = $this->email;
             $item['groups'] = isset($_POST['groups']) ? $_POST['groups'] : array();
             // loop the fields
             foreach ($this->customFields as $field) {
                 // shorten the field
                 $txtField = $field['formElements']['txtField'];
                 // add the value to the custom fields to store
                 $this->record['custom_fields'][$this->group['id']][$field['label']] = $txtField->getValue();
             }
             /*
              * This is, in fact, an unsubscribe of the subscriber's current groups, and a re-subscribe of the
              * groups he requested. This is done because the CM API supports no updateSubscriber function, and it
              * overwrites the values of custom fields if you do an update for 1 list and don't provide values for another.
              *
              * NOTE: A user will still be in the suppression list if he is resubscribed, but he will receive e-mails.
              * 		 (see: http://www.campaignmonitor.com/forums/viewtopic.php?id=1761)
              */
             // the groups the user is currently subscribed to
             if (!empty($this->record['groups'])) {
                 // loop the groups
                 foreach ($this->record['groups'] as $group) {
                     // Check if this group is in the allowed list. If it is, it should not be unsubscribed
                     if (!empty($item['groups']) && in_array($group, $item['groups'])) {
                         continue;
                     }
                     // unsubscribe the user
                     BackendMailmotorCMHelper::unsubscribe($this->email, $group);
                 }
             }
             // the groups the user wants to keep
             if (!empty($item['groups'])) {
                 // loop the groups
                 foreach ($item['groups'] as $group) {
                     // continue looping if this group has no custom fields
                     $customFields = !empty($this->record['custom_fields'][$group]) ? $this->record['custom_fields'][$group] : null;
                     // resubscribe for this group
                     BackendMailmotorCMHelper::subscribe($this->email, $group, $customFields);
                 }
             }
             // trigger event
             BackendModel::triggerEvent($this->getModule(), 'after_edit_address', array('item' => $this->record));
             // everything is saved, so redirect to the overview
             $this->redirect(BackendModel::createURLForAction('addresses') . (!empty($this->subscriptions) ? '&group_id=' . $ddmGroups->getValue() : '') . '&report=edited&var=' . urlencode($item['email']) . '&highlight=email-' . $item['email']);
         }
     }
 }