/**
  * @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;
 }
 /**
  * @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;
     }
 }
 /**
  * @param SproutEmail_CampaignModel $campaign
  * @param string $tab
  *
  * @throws \Exception
  * @return int CampaignRecordId
  */
 public function saveCampaign(SproutEmail_CampaignModel $campaign, $tab = 'info')
 {
     $oldCampaign = null;
     if (is_numeric($campaign->id)) {
         $campaignRecord = SproutEmail_CampaignRecord::model()->findById($campaign->id);
         $oldCampaign = SproutEmail_CampaignModel::populateModel($campaignRecord);
     } else {
         $campaignRecord = new SproutEmail_CampaignRecord();
     }
     $transaction = craft()->db->getCurrentTransaction() === null ? craft()->db->beginTransaction() : null;
     // @todo - Refactor. We no longer use tabs in the CP section.
     switch ($tab) {
         case 'fields':
             $fieldLayout = $campaign->getFieldLayout();
             craft()->fields->saveLayout($fieldLayout);
             // Delete our previous record
             if ($campaign->id && $oldCampaign && $oldCampaign->fieldLayoutId) {
                 craft()->fields->deleteLayoutById($oldCampaign->fieldLayoutId);
             }
             // Assign our new layout id info to our
             // form model and records
             $campaign->fieldLayoutId = $fieldLayout->id;
             $campaignRecord->fieldLayoutId = $fieldLayout->id;
             $campaignRecord = $this->saveCampaignInfo($campaign);
             if ($campaignRecord->hasErrors()) {
                 if ($transaction) {
                     $transaction->rollBack();
                 }
                 return $campaign;
             }
             break;
             // save the campaign
         default:
             if ($campaign->type == 'notification') {
                 $campaign->type = Campaign::Notification;
             } else {
                 $campaign->type = Campaign::Email;
             }
             try {
                 // Save the Campaign
                 $campaignRecord = $this->saveCampaignInfo($campaign);
                 // Rollback if saving fails
                 if ($campaignRecord->hasErrors()) {
                     $transaction->rollBack();
                     return $campaign;
                 }
                 // If we have a Notification, also Save the Entry
                 if ($campaign->type == Campaign::Notification) {
                     if (isset($oldCampaign->id)) {
                         $criteria = craft()->elements->getCriteria('SproutEmail_Entry');
                         $criteria->campaignId = $oldCampaign->id;
                         $entry = $criteria->first();
                     }
                     if (isset($entry)) {
                         // if we have a blast already, update it
                         $entry->campaignId = $campaignRecord->id;
                         $entry->subjectLine = $entry->subjectLine != '' ? $entry->subjectLine : $campaign->name;
                         $entry->getContent()->title = $campaign->name;
                     } else {
                         // If we don't have a blast yet, create a new entry
                         $entry = new SproutEmail_EntryModel();
                         $entry->campaignId = $campaignRecord->id;
                         $entry->subjectLine = $campaign->name;
                         $entry->getContent()->title = $campaign->name;
                     }
                     if (sproutEmail()->entries->saveEntry($entry, $campaign)) {
                         // @todo - redirect and such
                     } else {
                         SproutEmailPlugin::log(json_encode($entry->getErrors()));
                     }
                 }
             } catch (\Exception $e) {
                 SproutEmailPlugin::log(json_encode($e));
                 throw new Exception(Craft::t('Error: Campaign could not be saved.'));
             }
             break;
     }
     if ($transaction) {
         $transaction->commit();
     }
     return SproutEmail_CampaignModel::populateModel($campaignRecord);
 }
 /**
  * Populates an element model based on a query result.
  *
  * @param array $row
  *
  * @return array
  */
 public function populateElementModel($row)
 {
     return SproutEmail_EntryModel::populateModel($row);
 }
 /**
  * @param SproutEmail_CampaignModel $campaign
  * @param mixed|null                $element
  *
  * @return bool
  */
 public function sendNotification(SproutEmail_CampaignModel $campaign, $element = null)
 {
     if (count($campaign->entries)) {
         $email = new EmailModel();
         foreach ($campaign->entries as $entry) {
             $listIds = array();
             $recipientLists = $this->getRecipientListsByEntryId($entry->id);
             $entryRecipients = $this->getRecipientsFromEntryModel($entry);
             $dynamicRecipients = sproutEmail()->notifications->getDynamicRecipientsFromElement($element);
             if ($recipientLists && count($recipientLists)) {
                 foreach ($recipientLists as $list) {
                     $listIds[] = $list->id;
                 }
             }
             $entry = SproutEmail_EntryModel::populateModel($entry);
             $listRecipients = $this->getRecipientsByRecipientListIds($listIds);
             $recipients = array_merge($listRecipients, $entryRecipients, $dynamicRecipients);
             if ($recipients && count($recipients)) {
                 $email->subject = sproutEmail()->renderObjectTemplateSafely($entry->subjectLine, $element);
                 $email->fromName = sproutEmail()->renderObjectTemplateSafely($entry->fromName, $element);
                 $email->fromEmail = sproutEmail()->renderObjectTemplateSafely($entry->fromEmail, $element);
                 $email->replyTo = sproutEmail()->renderObjectTemplateSafely($entry->replyTo, $element);
                 if (strpos($email->replyTo, '{') === 0) {
                     $email->replyTo = $email->fromEmail;
                 }
                 sproutEmail()->renderObjectContentSafely($entry, $element);
                 $vars = sproutEmail()->notifications->prepareNotificationTemplateVariables($entry, $element);
                 $email->body = sproutEmail()->renderSiteTemplateIfExists($campaign->template . '.txt', $vars);
                 $email->htmlBody = sproutEmail()->renderSiteTemplateIfExists($campaign->template, $vars);
                 if (!empty($email->htmlBody)) {
                     foreach ($recipients as $recipient) {
                         $email->toEmail = sproutEmail()->renderObjectTemplateSafely($recipient->email, $element);
                         $email->toFirstName = $recipient->firstName;
                         $email->toLastName = $recipient->lastName;
                         try {
                             craft()->email->sendEmail($email);
                         } catch (\Exception $e) {
                             sproutEmail()->error($e->getMessage());
                         }
                     }
                     return true;
                 }
             } else {
                 sproutEmail()->error(Craft::t("No recipients found."));
             }
         }
     }
     return false;
 }
Esempio n. 6
0
 /**
  * Returns a notification entry model if found by campaing id
  *
  * @param int $id
  *
  * @return SproutEmail_EntryModel|null
  */
 public function getNotificationEntryByCampaignId($id)
 {
     $record = SproutEmail_EntryRecord::model()->findByAttributes(array('campaignId' => $id));
     if ($record) {
         return SproutEmail_EntryModel::populateModel($record);
     }
 }
    /**
     * 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);
        }
    }
 /**
  * Populates a SproutEmail_EntryModel with post data
  *
  * @param SproutEmail_EntryModel $entry
  *
  * @return \Craft\SproutEmail_EntryModel
  */
 protected function populateEntryModel(SproutEmail_EntryModel $entry)
 {
     $entry->campaignId = $this->campaign->id;
     $entry->slug = craft()->request->getPost('slug', $entry->slug);
     $entry->enabled = (bool) craft()->request->getPost('enabled', $entry->enabled);
     $entry->fromName = craft()->request->getPost('sproutEmail.fromName');
     $entry->fromEmail = craft()->request->getPost('sproutEmail.fromEmail');
     $entry->replyTo = craft()->request->getPost('sproutEmail.replyTo');
     $entry->subjectLine = craft()->request->getRequiredPost('subjectLine');
     $entry->getContent()->title = $entry->subjectLine;
     if (empty($entry->slug)) {
         $entry->slug = ElementHelper::createSlug($entry->subjectLine);
     }
     $fieldsLocation = craft()->request->getParam('fieldsLocation', 'fields');
     $entry->setContentFromPost($fieldsLocation);
     $entry->setContentPostLocation($fieldsLocation);
     return $entry;
 }