public function prepareParams(Event $event)
 {
     $user = craft()->users->getUserByUsernameOrEmail($event->params['username']);
     if ($user) {
         return array('value' => $user);
     }
     sproutEmail()->error('No user found with username/email ' . $event->params['username']);
 }
 /**
  * Renders the notification settings template with passed in route variables
  *
  * @param array $variables
  *
  * @throws HttpException
  */
 public function actionNotificationSettingsTemplate(array $variables = array())
 {
     if (isset($variables['campaignId'])) {
         if (!isset($variables['campaign'])) {
             $variables['campaign'] = sproutEmail()->campaigns->getCampaignById($variables['campaignId']);
         }
     } else {
         $variables['campaign'] = new SproutEmail_CampaignModel();
     }
     $variables['isMailerInstalled'] = (bool) sproutEmail()->mailers->isInstalled('defaultmailer');
     $this->renderTemplate('sproutemail/settings/notifications/_edit', $variables);
 }
 public function actionCampaignSettingsTemplate(array $variables = array())
 {
     if (isset($variables['campaignId'])) {
         // If campaign already exists, we're returning an error object
         if (!isset($variables['campaign'])) {
             $variables['campaign'] = sproutEmail()->campaigns->getCampaignById($variables['campaignId']);
         }
     } else {
         $variables['campaign'] = new SproutEmail_Campaign();
     }
     // Load our template
     $this->renderTemplate('sproutemail/settings/campaigns/_edit', $variables);
 }
 /**
  * @param SproutEmail_EntryModel    $entry
  * @param SproutEmail_CampaignModel $campaign
  *
  * @throws Exception
  * @throws \CDbException
  * @throws \Exception
  *
  * @return bool
  */
 public function saveEntry(SproutEmail_EntryModel $entry, SproutEmail_CampaignModel $campaign)
 {
     $isNewEntry = !$entry->id;
     if ($entry->id) {
         $entryRecord = SproutEmail_EntryRecord::model()->findById($entry->id);
         if (!$entryRecord) {
             throw new Exception(Craft::t('No entry exists with the ID “{id}”', array('id' => $entry->id)));
         }
     } else {
         $entryRecord = new SproutEmail_EntryRecord();
     }
     $entryRecord->campaignId = $entry->campaignId;
     $entryRecord->subjectLine = $entry->subjectLine;
     $entryRecord->setAttributes($entry->getAttributes());
     $entryRecord->setAttribute('recipients', $this->getOnTheFlyRecipients());
     $entryRecord->validate();
     $entry->addErrors($entryRecord->getErrors());
     if (!$entry->hasErrors()) {
         $transaction = craft()->db->getCurrentTransaction() === null ? craft()->db->beginTransaction() : null;
         try {
             if (craft()->elements->saveElement($entry)) {
                 // Now that we have an element ID, save it on the other stuff
                 if ($isNewEntry) {
                     $entryRecord->id = $entry->id;
                 }
                 $entryRecord->save(false);
                 $notificationEvent = craft()->request->getPost('notificationEvent');
                 sproutEmail()->mailers->saveRecipientLists($campaign, $entry);
                 if (!$notificationEvent || sproutEmail()->notifications->save($notificationEvent, $campaign->id)) {
                     if ($transaction && $transaction->active) {
                         $transaction->commit();
                     }
                     return true;
                 }
             }
         } catch (\Exception $e) {
             if ($transaction && $transaction->active) {
                 $transaction->rollback();
             }
             throw $e;
         }
     }
     return false;
 }
 /**
  * Gives us the ability to render campaign previews by using the Craft API and templates/render
  *
  * @param BaseElementModel $element
  *
  * @return array|bool|mixed
  */
 public function routeRequestForMatchedElement(BaseElementModel $element)
 {
     $campaign = sproutEmail()->campaigns->getCampaignById($element->campaignId);
     if (!$campaign) {
         return false;
     }
     $extension = null;
     if ($type = craft()->request->getQuery('type')) {
         $extension = in_array(strtolower($type), array('txt', 'text')) ? '.txt' : null;
     }
     if (!craft()->templates->doesTemplateExist($campaign->template . $extension)) {
         $templateName = $campaign->template . $extension;
         sproutEmail()->error(Craft::t("The template '{templateName}' could not be found", array('templateName' => $templateName)));
     }
     $vars = array('entry' => $element, 'campaign' => $campaign, 'recipient' => array('firstName' => '{firstName}', 'lastName' => '{lastName}', 'email' => '{email}'), 'firstName' => '{firstName}', 'lastName' => '{lastName}', 'email' => '{email}');
     return array('action' => 'templates/render', 'params' => array('template' => $campaign->template . $extension, 'variables' => $vars));
 }
 /**
  * Handles sproutCommerce.checkoutEnd events to add dynamic recipients to a lists
  *
  * @param Event $event
  */
 public function handleCheckoutEnd(Event $event)
 {
     if (isset($event->params['checkout']->success) && $event->params['checkout']->success) {
         $order = $event->params['checkout']->order;
         if (count($order->products) && count($order->payments)) {
             foreach ($order->products as $purchasedProduct) {
                 $list = sproutEmailDefaultMailer()->getRecipientListByHandle($purchasedProduct->product->slug);
                 if ($list) {
                     foreach ($order->payments as $payment) {
                         $recipient = new SproutEmail_DefaultMailerRecipientModel();
                         $recipient->email = $payment->email;
                         $recipient->firstName = $payment->firstName;
                         $recipient->lastName = $payment->lastName;
                         $recipient->recipientLists = array($list->id);
                         try {
                             if (!sproutEmailDefaultMailer()->saveRecipient($recipient)) {
                                 sproutEmail()->error($recipient->getErrors());
                             }
                         } catch (\Exception $e) {
                             sproutEmail()->error($e->getMessage());
                         }
                     }
                 }
             }
         }
     }
 }
 /**
  * Deletes a mailer record by name
  *
  * @param string $name
  *
  * @return bool
  */
 protected function deleteMailerRecord($name)
 {
     $record = $this->getMailerRecordByName($name);
     if (!$record) {
         sproutEmail()->error(Craft::t('No {name} mailer record to delete.', array('name' => $name)));
         return false;
     }
     try {
         return $record->delete();
     } catch (\Exception $e) {
         $vars = array('name' => $name, 'message' => PHP_EOL . $e->getMessage());
         sproutEmail()->error(Craft::t('Unable to delete the {name} mailer record.{message}', $vars));
     }
 }
 /**
  * @param SproutEmail_EntryModel    $entry
  * @param SproutEmail_CampaignModel $campaign
  *
  * @return string
  */
 public function getPrepareModalHtml(SproutEmail_EntryModel $entry, SproutEmail_CampaignModel $campaign)
 {
     $lists = sproutEmail()->entries->getRecipientListsByEntryId($entry->id);
     $recipientLists = array();
     if (count($lists)) {
         foreach ($lists as $list) {
             $recipientList = sproutEmailDefaultMailer()->getRecipientListById($list->list);
             if ($recipientList) {
                 $recipientLists[] = $recipientList;
             }
         }
     }
     return craft()->templates->render('sproutemail/_modals/prepare', array('entry' => $entry, 'campaign' => $campaign, 'recipientLists' => $recipientLists));
 }
 public function getRecipientLists($mailer)
 {
     return sproutEmail()->mailers->getRecipientLists($mailer);
 }
    /**
     * Install example data
     *
     * @return void
     */
    private function _installExampleData()
    {
        try {
            // Create Example Emails
            // ------------------------------------------------------------
            $emailSettings = array(array('name' => 'Welcome Email - User Notification', 'handle' => 'welcomeEmail', 'type' => 'notification', 'mailer' => 'defaultmailer', 'hasUrls' => false, 'urlFormat' => null, 'hasAdvancedTitles' => false, 'template' => 'sproutemail/notification', 'templateCopyPaste' => null), array('name' => 'New User - Admin Notification', 'handle' => 'newUserEmail', 'type' => 'notification', 'mailer' => 'defaultmailer', 'hasUrls' => false, 'urlFormat' => null, 'hasAdvancedTitles' => false, 'template' => 'sproutemail/notification', 'templateCopyPaste' => null), array('name' => 'Monthly Newsletter', 'handle' => 'monthlyNewsletter', 'type' => 'email', 'mailer' => 'copypaste', 'hasUrls' => true, 'hasAdvancedTitles' => false, 'urlFormat' => 'sproutemail/{slug}', 'template' => 'sproutemail/newsletter', 'templateCopyPaste' => 'sproutemail/newsletter'));
            $fieldSettings = array('welcomeEmail' => array('Content' => array(array('name' => 'HTML Email Body', 'handle' => 'exampleHtmlEmailBody', 'instructions' => '', 'type' => 'RichText', 'required' => 1, 'settings' => array('configFile' => '', 'cleanupHtml' => '1', 'purifyHtml' => '', 'columnType' => 'text')), array('name' => 'Text Email Body', 'handle' => 'exampleTextEmailBody', 'type' => 'PlainText', 'required' => 1, 'settings' => array('placeholder' => '', 'maxLength' => '', 'multiline' => 1, 'initialRows' => 4)))), 'newUserEmail' => array('Content' => array(array('name' => 'HTML Email Body', 'handle' => 'exampleHtmlEmailBody', 'instructions' => '', 'type' => 'RichText', 'required' => 1, 'settings' => array('configFile' => '', 'cleanupHtml' => '1', 'purifyHtml' => '', 'columnType' => 'text')), array('name' => 'Text Email Body', 'handle' => 'exampleTextEmailBody', 'type' => 'PlainText', 'required' => 1, 'settings' => array('placeholder' => '', 'maxLength' => '', 'multiline' => 1, 'initialRows' => 4)))), 'monthlyNewsletter' => array('Content' => array(array('name' => 'HTML Email Body', 'handle' => 'exampleHtmlEmailBody', 'instructions' => '', 'type' => 'RichText', 'required' => 1, 'settings' => array('configFile' => '', 'cleanupHtml' => '1', 'purifyHtml' => '', 'columnType' => 'text')), array('name' => 'Text Email Body', 'handle' => 'exampleTextEmailBody', 'type' => 'PlainText', 'required' => 1, 'settings' => array('placeholder' => '', 'maxLength' => '', 'multiline' => 1, 'initialRows' => 4)))));
            $currentUser = craft()->userSession->getUser();
            $emailExamples = array('welcomeEmail' => array('title' => 'Welcome!', 'subjectLine' => 'Welcome!', 'slug' => 'welcome', 'uri' => null, 'campaignId' => null, 'sproutEmail' => array('fromName' => craft()->getSiteName(), 'fromEmail' => $currentUser->email, 'replyTo' => $currentUser->email), 'recipient' => array('onTheFlyRecipients' => '{email}'), 'rules' => array('craft' => array('saveUser' => array('whenNew' => '1', 'whenUpdated' => '', 'userGroupIds' => ''))), 'enabled' => true, 'archived' => '0', 'locale' => $currentUser->locale, 'localeEnabled' => '1', 'sent' => '0', 'htmlBody' => '<p>Thanks for becoming a member.</p>
<ul>
	<li>Username: <strong>{username}</strong></li>
	<li>Email: <strong>{email}</strong></li>
</ul>', 'textBody' => 'Thanks for becoming a member.

Username: {username}
Email: {email}'), 'newUserEmail' => array('title' => 'A new user has created an account', 'subjectLine' => 'A new user has created an account', 'slug' => 'a-new-user-has-created-an-account', 'uri' => null, 'campaignId' => null, 'sproutEmail' => array('fromName' => craft()->getSiteName(), 'fromEmail' => $currentUser->email, 'replyTo' => $currentUser->email), 'recipient' => array('onTheFlyRecipients' => $currentUser->email), 'rules' => array('craft' => array('saveUser' => array('whenNew' => '1', 'whenUpdated' => '', 'userGroupIds' => ''))), 'enabled' => true, 'archived' => '0', 'locale' => $currentUser->locale, 'localeEnabled' => '1', 'sent' => '0', 'htmlBody' => '<p>A new user has been created:</p>
<ul>
	<li>Username: <strong>{username}</strong></li>
	<li>Email: <strong>{email}</strong></li>
</ul>', 'textBody' => 'A new user has been created:

Username: {username}
Email: {email}'), 'monthlyNewsletter' => array('title' => 'Best Practices for your Email Subject Line', 'subjectLine' => 'Best Practices for your Email Subject Line', 'slug' => 'best-practices-for-your-email-subject-line', 'uri' => 'sproutemail/best-practices-for-your-email-subject-line', 'campaignId' => null, 'sproutEmail' => array('fromName' => craft()->getSiteName(), 'fromEmail' => $currentUser->email, 'replyTo' => $currentUser->email), 'recipient' => array(), 'rules' => array(), 'enabled' => true, 'archived' => '0', 'locale' => $currentUser->locale, 'localeEnabled' => '1', 'sent' => '0', 'htmlBody' => '<p>Say something interesting!</p>', 'textBody' => 'Say something interesting!'));
            // Create Emails and their Content
            foreach ($emailSettings as $settings) {
                $campaign = new SproutEmail_CampaignModel();
                // Assign our email settings
                $campaign->name = $settings['name'];
                $campaign->handle = $settings['handle'];
                $campaign->type = $settings['type'];
                $campaign->mailer = $settings['mailer'];
                $campaign->hasUrls = $settings['hasUrls'];
                $campaign->urlFormat = $settings['urlFormat'];
                $campaign->hasAdvancedTitles = $settings['hasAdvancedTitles'];
                $campaign->template = $settings['template'];
                $campaign->templateCopyPaste = $settings['templateCopyPaste'];
                // Only install our campaign example if CopyPaste Mailer is installed
                if ($campaign->mailer == 'copypaste' && !craft()->plugins->getPlugin('SproutEmailCopyPaste')) {
                    break;
                }
                // Create the Email
                if (!($campaign = sproutEmail()->campaigns->saveCampaign($campaign))) {
                    SproutEmailPlugin::log('Campaign NOT CREATED');
                    return false;
                }
                //------------------------------------------------------------
                // Do we have a new field that doesn't exist yet?
                // If so, save it and grab the id.
                $fieldLayout = array();
                $requiredFields = array();
                $tabs = $fieldSettings[$campaign->handle];
                // Ensure we have a Field Group to save our Fields
                if (!($sproutEmailFieldGroup = $this->_createFieldGroup())) {
                    SproutEmailPlugin::log('Could not save the Sprout Email Examples field group.', LogLevel::Warning);
                    craft()->userSession->setError(Craft::t('Unable to create examples. Field group not saved.'));
                    return false;
                }
                foreach ($tabs as $tabName => $newFields) {
                    foreach ($newFields as $newField) {
                        if (!($field = craft()->fields->getFieldByHandle($newField['handle']))) {
                            $field = new FieldModel();
                            $field->groupId = $sproutEmailFieldGroup->id;
                            $field->name = $newField['name'];
                            $field->handle = $newField['handle'];
                            $field->type = $newField['type'];
                            $field->required = $newField['required'];
                            $field->settings = $newField['settings'];
                            // Save our field
                            craft()->fields->saveField($field);
                        }
                        $fieldLayout[$tabName][] = $field->id;
                        if ($field->required) {
                            $requiredFields[] = $field->id;
                        }
                    }
                }
                // Set the field layout
                $fieldLayout = craft()->fields->assembleLayout($fieldLayout, $requiredFields);
                $fieldLayout->type = 'SproutEmail_Campaign';
                $campaign->setFieldLayout($fieldLayout);
                // Save our email again with a layout
                sproutEmail()->campaigns->saveCampaign($campaign, 'fields');
                $entryRecord = SproutEmail_EntryRecord::model()->findByAttributes(array('campaignId' => $campaign->id));
                if (!$entryRecord) {
                    $entry = new SproutEmail_EntryModel();
                } else {
                    $entry = SproutEmail_EntryModel::populateModel($entryRecord->getAttributes());
                }
                $entryData = $emailExamples[$campaign->handle];
                $_POST['sproutEmail'] = $entryData['sproutEmail'];
                $_POST['recipient'] = $entryData['recipient'];
                $_POST['rules'] = $entryData['rules'];
                unset($entryData['recipient']);
                unset($entryData['rules']);
                $entry->setAttributes($entryData);
                $entry->campaignId = $campaign->id;
                $entry->fromName = craft()->request->getPost('sproutEmail.fromName');
                $entry->fromEmail = craft()->request->getPost('sproutEmail.fromEmail');
                $entry->replyTo = craft()->request->getPost('sproutEmail.replyTo');
                $entry->getContent()->title = $entryData['title'];
                $entry->getContent()->exampleHtmlEmailBody = $entryData['htmlBody'];
                $entry->getContent()->exampleTextEmailBody = $entryData['textBody'];
                sproutEmail()->entries->saveEntry($entry, $campaign);
                if ($campaign->type == 'notification') {
                    sproutEmail()->notifications->save('users-saveUser', $campaign->id);
                }
            }
        } catch (\Exception $e) {
            $this->_handleError($e);
        }
    }
 /**
  * Installs all available mailers if any
  */
 public function onAfterInstall()
 {
     try {
         if (!$this->getIsInitialized()) {
             $this->init();
         }
         sproutEmail()->mailers->installMailers();
         // Redirect to examples after installation
         craft()->request->redirect(UrlHelper::getCpUrl() . '/sproutemail/examples');
     } catch (\Exception $e) {
         sproutEmail()->error($e->getMessage());
     }
 }
 /**
  * @return SproutEmail_CampaignModel
  */
 public function getType()
 {
     $campaign = sproutEmail()->campaigns->getCampaignById($this->campaignId);
     return $campaign;
 }
 /**
  * Returns the mailer title optionally wrapped in a link pointing to /sproutemail/mailer
  *
  * @note
  * We use this to integrate third party plugin routes and UI seamlessly within Sprout Email
  *
  * @see       hasCpSection()
  *
  * @deprecate Deprecated for 0.9.0 in favour of getCpSectionUrl()
  *
  * @return string|\Twig_Markup
  */
 public final function getCpTitle()
 {
     if ($this->hasCpSection()) {
         return sproutEmail()->mailers->getMailerCpSectionLink($this);
     }
     return $this->getTitle();
 }
 /**
  * Fetch or create a SproutEmail_EntryModel
  *
  * @throws Exception
  * @return SproutEmail_EntryModel
  */
 protected function getEntryModel()
 {
     $entryId = craft()->request->getPost('entryId');
     if ($entryId) {
         $entry = sproutEmail()->entries->getEntryById($entryId);
         if (!$entry) {
             throw new Exception(Craft::t('No entry exists with the ID “{id}”', array('id' => $entryId)));
         }
     } else {
         $entry = new SproutEmail_EntryModel();
     }
     return $entry;
 }
Example #15
0
 /**
  * Installs all available mailers if any
  */
 public function onAfterInstall()
 {
     try {
         if (!$this->getIsInitialized()) {
             $this->init();
         }
         sproutEmail()->mailers->installMailers();
     } catch (\Exception $e) {
         sproutEmail()->error($e->getMessage());
     }
 }
 /**
  * Custom email provider validator
  *
  * @param string $attribute
  *
  * @return void
  */
 public function validMailer($attribute)
 {
     if (!($mailers = sproutEmail()->mailers->getInstalledMailers()) || !array_key_exists($this->{$attribute}, $mailers)) {
         $this->addError($attribute, Craft::t('Invalid email provider.'));
     }
 }
 /**
  * Deletes a campaign by its ID along with associations;
  * also cleans up any remaining orphans
  *
  * @param int $campaignId
  *
  * @return bool
  */
 public function deleteCampaign($campaignId)
 {
     try {
         craft()->db->createCommand()->delete('sproutemail_campaigns', array('id' => $campaignId));
         // This only applies to Notifications
         sproutEmail()->notifications->deleteNotificationsByCampaignId($campaignId);
         return true;
     } catch (\Exception $e) {
         return false;
     }
 }
 /**
  * @param SproutEmail_EntryModel $entry
  *
  * @throws \CDbException
  * @throws \Exception
  *
  * @return bool
  */
 public function deleteEntry(SproutEmail_EntryModel $entry)
 {
     $transaction = craft()->db->getCurrentTransaction() === null ? craft()->db->beginTransaction() : null;
     try {
         // Delete Campaign and Rules associated with this email
         if ($entry->getType() == Campaign::Notification) {
             sproutEmail()->campaigns->deleteCampaign($entry->campaignId);
         }
         // Delete the Element and Entry
         craft()->elements->deleteElementById($entry->id);
         if ($transaction !== null) {
             $transaction->commit();
         }
         return true;
     } catch (\Exception $e) {
         if ($transaction !== null) {
             $transaction->rollback();
         }
         throw $e;
     }
 }
 /**
  * @throws Exception
  * @throws HttpException
  */
 public function actionSaveRecipientList()
 {
     $this->requirePostRequest();
     $id = craft()->request->getPost('id');
     if ($id && is_numeric($id)) {
         $model = sproutEmailDefaultMailer()->getRecipientListById($id);
         if (!$model) {
             throw new Exception(Craft::t('Recipient list with id ({id}) was not found.', array('id' => $id)));
         }
     } else {
         $model = new SproutEmail_DefaultMailerRecipientListModel();
     }
     $name = craft()->request->getPost('name', $model->name);
     $model->setAttribute('name', $name);
     $model->setAttribute('handle', sproutEmail()->createHandle($name));
     if ($model->validate() && sproutEmailDefaultMailer()->saveRecipientList($model)) {
         craft()->userSession->setNotice(Craft::t('Recipient list saved successfully.'));
         if (craft()->request->isAjaxRequest()) {
             $this->returnJson(array('success' => 'true', 'list' => array('id' => $model->id)));
         }
         $this->redirectToPostedUrl($model);
     }
     craft()->userSession->setError(Craft::t('Unable to save recipient list.'));
     if (craft()->request->isAjaxRequest()) {
         $this->returnErrorJson(Craft::t('Unable to save recipient list.'));
     }
     craft()->urlManager->setRouteVariables(array('recipientList' => $model));
 }
 /**
  * Provides a way for mailers to render content to perform actions inside a modal window
  *
  * @throws HttpException
  */
 public function actionGetPreviewModal()
 {
     $this->requirePostRequest();
     $this->requireAjaxRequest();
     $mailer = craft()->request->getRequiredPost('mailer');
     $entryId = craft()->request->getRequiredPost('entryId');
     $campaignId = craft()->request->getRequiredPost('campaignId');
     $modal = sproutEmail()->mailers->getPreviewModal($mailer, $entryId, $campaignId);
     $this->returnJson($modal->getAttributes());
 }
 /**
  * @param SproutEmail_CampaignModel $campaign
  * @param mixed                     $element Will be an element model most of the time
  *
  * @throws Exception
  * @throws \Exception
  * @return mixed
  */
 protected function relayNotificationThroughAssignedMailer(SproutEmail_CampaignModel $campaign, $element)
 {
     if (!isset($campaign->mailer)) {
         throw new Exception(Craft::t('An email provider is required to send the notification.'));
     }
     $mailer = sproutEmail()->mailers->getMailerByName($campaign->mailer);
     if (!$mailer) {
         throw new Exception(Craft::t('The email provider {mailer} is not available.', array('mailer' => $campaign->mailer)));
     }
     if (!method_exists($mailer, 'sendNotification')) {
         throw new Exception(Craft::t('The {mailer} does not have a sendNotification() method.', array('mailer' => get_class($mailer))));
     }
     // Forces campaign.entries to be populated with live entries only
     $campaign->setLiveEntries();
     try {
         return $mailer->sendNotification($campaign, $element);
     } catch (\Exception $e) {
         throw $e;
     }
 }
 public function doesSiteTemplateExist($template)
 {
     return sproutEmail()->doesSiteTemplateExist($template);
 }