/**
  * @return bool
  */
 public function safeUp()
 {
     if ($table = $this->dbConnection->schema->getTable('{{sproutemail_campaigns_notifications}}')) {
         if ($table->getColumn('options') != null) {
             $notifications = craft()->db->createCommand()->select('id, eventId, options')->from('sproutemail_campaigns_notifications')->where(array('in', 'eventId', array('entries-saveEntry', 'users-saveUser')))->queryAll();
             if ($count = count($notifications)) {
                 SproutEmailPlugin::log('Notifications found: ' . $count, LogLevel::Info, true);
                 $newOptions = array();
                 foreach ($notifications as $notification) {
                     switch ($notification['eventId']) {
                         case 'entries-saveEntry':
                             SproutEmailPlugin::log('Migrating Craft saveEntry notification', LogLevel::Info, true);
                             $newOptions = $this->_updateSaveEntryOptions($notification['options']);
                             break;
                         case 'users-saveUser':
                             SproutEmailPlugin::log('Migrating Craft saveUser notification', LogLevel::Info, true);
                             $newOptions = $this->_updateSaveUserOptions($notification['options']);
                             break;
                     }
                     craft()->db->createCommand()->update('sproutemail_campaigns_notifications', array('options' => $newOptions), 'id= :id', array(':id' => $notification['id']));
                     SproutEmailPlugin::log('Migration of notification complete', LogLevel::Info, true);
                 }
             }
             SproutEmailPlugin::log('No notifications found to migrate.', LogLevel::Info, true);
         } else {
             SproutEmailPlugin::log('Could not find the `options` column.', LogLevel::Info, true);
         }
     } else {
         SproutEmailPlugin::log('Could not find the `sproutemail_campaigns_notifications` table.', LogLevel::Info, true);
     }
     return true;
 }
 /**
  * Returns whether or not the entry meets the criteria necessary to trigger the event
  *
  * @param mixed      $options
  * @param EntryModel $entry
  * @param array      $params
  *
  * @return bool
  */
 public function validateOptions($options, EntryModel $entry, array $params = array())
 {
     $isNewEntry = isset($params['isNewEntry']) && $params['isNewEntry'];
     $whenNew = isset($options['craft']['saveEntry']['whenNew']) && $options['craft']['saveEntry']['whenNew'];
     $whenUpdated = isset($options['craft']['saveEntry']['whenUpdated']) && $options['craft']['saveEntry']['whenUpdated'];
     SproutEmailPlugin::log(Craft::t("Sprout Email '" . $this->getTitle() . "' event has been triggered"));
     // If any section ids were checked, make sure the entry belongs in one of them
     if (!empty($options['craft']['saveEntry']['sectionIds']) && count($options['craft']['saveEntry']['sectionIds'])) {
         if (!in_array($entry->getSection()->id, $options['craft']['saveEntry']['sectionIds'])) {
             SproutEmailPlugin::log(Craft::t('Saved entry not in any selected Section.'));
             return false;
         }
     }
     if (!$whenNew && !$whenUpdated) {
         SproutEmailPlugin::log(Craft::t("No settings have been selected. Please select 'When an entry is created' or 'When\n\t\t\tan entry is updated' from the options on the Rules tab."));
         return false;
     }
     // Make sure new entries are new
     if ($whenNew && !$isNewEntry && !$whenUpdated) {
         SproutEmailPlugin::log(Craft::t("No match. 'When an entry is created' is selected but the entry is being updated\n\t\t\t."));
         return false;
     }
     // Make sure updated entries are not new
     if ($whenUpdated && $isNewEntry && !$whenNew) {
         SproutEmailPlugin::log(Craft::t("No match. 'When an entry is updated' is selected but the entry is new."));
         return false;
     }
     return true;
 }
 /**
  * Returns whether or not the user meets the criteria necessary to trigger the event
  *
  * @param mixed     $options
  * @param UserModel $user
  * @param array     $params
  *
  * @return bool
  */
 public function validateOptions($options, UserModel $user, array $params = array())
 {
     $isNewUser = isset($params['isNewUser']) && $params['isNewUser'];
     $whenNew = isset($options['craft']['saveUser']['whenNew']) && $options['craft']['saveUser']['whenNew'];
     $whenUpdated = isset($options['craft']['saveUser']['whenUpdated']) && $options['craft']['saveUser']['whenUpdated'];
     SproutEmailPlugin::log(Craft::t("Sprout Email '" . $this->getTitle() . "' event has been triggered"));
     // If any user groups were checked, make sure the user is in one of the groups
     if (!empty($options['craft']['saveUser']['userGroupIds']) && count($options['craft']['saveUser']['userGroupIds'])) {
         $inGroup = false;
         $existingUserGroups = $user->getGroups('id');
         // When saving a new user, we grab our groups from the post request
         // because _processUserGroupsPermissions() runs after saveUser()
         $newUserGroups = craft()->request->getPost('groups');
         if (!is_array($newUserGroups)) {
             $newUserGroups = ArrayHelper::stringToArray($newUserGroups);
         }
         foreach ($options['craft']['saveUser']['userGroupIds'] as $groupId) {
             if (array_key_exists($groupId, $existingUserGroups) || in_array($groupId, $newUserGroups)) {
                 $inGroup = true;
             }
         }
         if (!$inGroup) {
             SproutEmailPlugin::log(Craft::t('Saved user not in any selected User Group.'));
             return false;
         }
     }
     if (!$whenNew && !$whenUpdated) {
         SproutEmailPlugin::log(Craft::t("No settings have been selected. Please select 'When a user is created' or 'When\n\t\t\ta user is updated' from the options on the Rules tab."));
         return false;
     }
     if ($whenNew && !$isNewUser && !$whenUpdated) {
         SproutEmailPlugin::log(Craft::t("No match. 'When a user is created' is selected but the user is being updated."));
         return false;
     }
     if ($whenUpdated && $isNewUser && !$whenNew) {
         SproutEmailPlugin::log(Craft::t("No match. 'When a user is updated' is selected but the user is new."));
         return false;
     }
     return true;
 }
コード例 #4
0
 /**
  * @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);
 }
コード例 #5
0
 /**
  * Logs an error in cases where it makes more sense than to throw an exception
  *
  * @param mixed $msg
  * @param array $vars
  */
 public function error($msg, array $vars = array())
 {
     if (is_string($msg)) {
         $msg = Craft::t($msg, $vars);
     } else {
         $msg = print_r($msg, true);
     }
     SproutEmailPlugin::log($msg, LogLevel::Error);
 }
 /**
  * Returns whether or not the user meets the criteria necessary to trigger the event
  *
  * @param mixed     $options
  * @param UserModel $user
  * @param array     $params
  *
  * @return bool
  */
 public function validateOptions($options, UserModel $user, array $params = array())
 {
     SproutEmailPlugin::log(Craft::t("Sprout Email '" . $this->getTitle() . "' event has been triggered"));
     return true;
 }
    /**
     * 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);
        }
    }
コード例 #8
0
 /**
  * @param mixed $message
  * @param array $vars
  */
 public function log($message, array $vars = array())
 {
     if (is_string($message)) {
         $message = Craft::t($message, $vars);
     } else {
         $message = print_r($message, true);
     }
     SproutEmailPlugin::log($message, LogLevel::Info);
 }
コード例 #9
0
 /**
  * @param SproutEmail_EntryModel $entry
  *
  * @throws HttpException
  */
 protected function showEntry(SproutEmail_EntryModel $entry, $template = null)
 {
     // @TODO
     // Grab Campaign
     // Make sure it exists
     // Get the template value from the Campaign settings
     // ------------------------------------------------------------
     $campaign = sproutEmail()->campaigns->getCampaignById($entry->campaignId);
     if ($campaign) {
         craft()->templates->getTwig()->disableStrictVariables();
         craft()->path->setTemplatesPath(craft()->path->getSiteTemplatesPath());
         $ext = '';
         if (in_array($template, array('txt', 'text'))) {
             $ext = '.txt';
         }
         $this->renderTemplate($campaign->template . $ext, array('entry' => $entry, 'campaign' => $campaign, 'firstName' => '{firstName}', 'lastName' => '{lastName}', 'email' => '{email}'));
     } else {
         SproutEmailPlugin::log('Attempting to preview an Entry that does not exist', LogLevel::Error);
         throw new HttpException(404);
     }
 }