/**
  * @see BaseJob::run()
  */
 public function run()
 {
     try {
         $originalUser = Yii::app()->user->userModel;
         Yii::app()->user->userModel = BaseControlUserConfigUtil::getUserToRunAs();
         $processedModelsCount = 0;
         $batchSize = $this->resolveBatchSize();
         if ($batchSize != null) {
             $resolvedBatchSize = $batchSize + 1;
         } else {
             $resolvedBatchSize = null;
         }
         foreach (WorkflowMessageInQueue::getModelsToProcess($resolvedBatchSize) as $workflowMessageInQueue) {
             if ($processedModelsCount < $batchSize || $batchSize == null) {
                 try {
                     $model = $this->resolveModel($workflowMessageInQueue);
                     $this->resolveSavedWorkflowIsValid($workflowMessageInQueue);
                     $this->processWorkflowMessageInQueue($workflowMessageInQueue, $model);
                 } catch (NotFoundException $e) {
                 }
                 $workflowMessageInQueue->delete();
                 $processedModelsCount++;
             } else {
                 Yii::app()->jobQueue->add('WorkflowMessageInQueue', 5);
                 break;
             }
         }
         Yii::app()->user->userModel = $originalUser;
         return true;
     } catch (MissingASuperAdministratorException $e) {
         //skip running workflow, since no super administrators are available.
         $this->errorMessage = Zurmo::t('WorkflowsModule', 'Could not process since no super administrators were found');
         return false;
     }
 }
 /**
  * Execute the action.
  * @param array command line parameters specific for this command
  */
 public function actionIndex($username, $password)
 {
     // we want to change password and while doing so it would be better to assume
     // a root-level system user.
     Yii::app()->user->userModel = BaseControlUserConfigUtil::getUserToRunAs(true);
     if (!isset($username)) {
         $this->usageError('A username must be specified.');
     }
     if (!isset($password)) {
         $this->usageError('You must specify the new password.');
     }
     try {
         $user = User::getByUsername($username);
     } catch (NotFoundException $e) {
         $this->usageError('The specified username does not exist.');
     }
     $user->setScenario('changePassword');
     $userPasswordForm = new UserPasswordForm($user);
     $userPasswordForm->setScenario('changePassword');
     $userPasswordForm->newPassword = $password;
     $userPasswordForm->newPassword_repeat = $password;
     if (!$userPasswordForm->validate()) {
         $this->addErrorsAsUsageErrors($userPasswordForm->getErrors());
     }
     if (!$user->validate()) {
         $this->addErrorsAsUsageErrors($user->getErrors());
     }
     if (!$user->save()) {
         throw new FailedToSaveModelException();
     }
     echo 'Updated Password' . "\n";
 }
 /**
  * Testing that each model type can render properly and does not throw an exception
  */
 public function testRenderSummaryContentWithEmailMessage()
 {
     $super = User::getByUsername('super');
     $billy = User::getByUsername('billy');
     $this->assertEquals(0, EmailMessage::getCount());
     $emailMessage = new EmailMessage();
     $emailMessage->owner = BaseControlUserConfigUtil::getUserToRunAs();
     $emailMessage->subject = 'My First Email';
     //Set sender, and recipient, and content
     $emailContent = new EmailMessageContent();
     $emailContent->textContent = 'My First Message';
     $emailContent->htmlContent = 'Some fake HTML content';
     $emailMessage->content = $emailContent;
     //Sending from the system, does not have a 'person'.
     $sender = new EmailMessageSender();
     $sender->fromAddress = '*****@*****.**';
     $sender->fromName = 'Zurmo System';
     $sender->personsOrAccounts->add($super);
     $emailMessage->sender = $sender;
     //Recipient is billy.
     $recipient = new EmailMessageRecipient();
     $recipient->toAddress = '*****@*****.**';
     $recipient->toName = 'Billy James';
     $recipient->type = EmailMessageRecipient::TYPE_TO;
     $recipient->personsOrAccounts->add($billy);
     $emailMessage->recipients->add($recipient);
     $box = EmailBox::resolveAndGetByName(EmailBox::NOTIFICATIONS_NAME);
     $emailMessage->folder = EmailFolder::getByBoxAndType($box, EmailFolder::TYPE_DRAFT);
     $saved = $emailMessage->save();
     $this->assertTrue($saved);
     $content = ActivitiesUtil::renderSummaryContent($emailMessage, 'someUrl', LatestActivitiesConfigurationForm::OWNED_BY_FILTER_ALL, 'HomeModule');
     $content = ActivitiesUtil::renderSummaryContent($emailMessage, 'someUrl', LatestActivitiesConfigurationForm::OWNED_BY_FILTER_USER, 'HomeModule');
     $content = ActivitiesUtil::renderSummaryContent($emailMessage, 'someUrl', LatestActivitiesConfigurationForm::OWNED_BY_FILTER_ALL, 'UserModule');
     $content = ActivitiesUtil::renderSummaryContent($emailMessage, 'someUrl', LatestActivitiesConfigurationForm::OWNED_BY_FILTER_USER, 'UserModule');
 }
 /**
  * @depends testGetUserToRunAsThrowNotFoundExceptionWhenUserDoesNotExist
  */
 public function testGetUserToRunAsCreatesBackendUserImplicitly()
 {
     $user = BaseControlUserConfigUtil::getUserToRunAs();
     $this->assertNotNull($user);
     $backendUser = User::getByUsername(BaseControlUserConfigUtil::USERNAME);
     $this->assertEquals($backendUser, $user);
 }
 /**
  * A notification email is different than a regular outbound email because it is owned by a super user
  * that is different than the user logged in.  So the sender does not have a 'person'
  */
 public function testCreateEmailMessageThatIsANotification()
 {
     $super = User::getByUsername('super');
     Yii::app()->user->userModel = $super;
     $billy = User::getByUsername('billy');
     $this->assertEquals(0, EmailMessage::getCount());
     $emailMessage = new EmailMessage();
     $emailMessage->owner = BaseControlUserConfigUtil::getUserToRunAs();
     $emailMessage->subject = 'My First Email';
     //Set sender, and recipient, and content
     $emailContent = new EmailMessageContent();
     $emailContent->textContent = 'My First Message';
     $emailContent->htmlContent = 'Some fake HTML content';
     $emailMessage->content = $emailContent;
     //Sending from the system, does not have a 'person'.
     $sender = new EmailMessageSender();
     $sender->fromAddress = '*****@*****.**';
     $sender->fromName = 'Zurmo System';
     $emailMessage->sender = $sender;
     //Recipient is billy.
     $recipient = new EmailMessageRecipient();
     $recipient->toAddress = '*****@*****.**';
     $recipient->toName = 'Billy James';
     $recipient->type = EmailMessageRecipient::TYPE_TO;
     $recipient->personsOrAccounts->add($billy);
     $emailMessage->recipients->add($recipient);
     //At this point the message is in no folder
     $this->assertTrue($emailMessage->folder->id < 0);
     $box = EmailBox::resolveAndGetByName(EmailBox::NOTIFICATIONS_NAME);
     $emailMessage->folder = EmailFolder::getByBoxAndType($box, EmailFolder::TYPE_DRAFT);
     //Save, at this point the email should be in the draft folder
     $saved = $emailMessage->save();
     $this->assertTrue($saved);
     $this->assertTrue($emailMessage->folder->id > 0);
     $this->assertEquals(0, EmailMessageSendError::getCount());
     $emailMessageSendError = new EmailMessageSendError();
     $data = array();
     $data['message'] = 'error message';
     $emailMessageSendError->serializedData = serialize($data);
     $emailMessage->folder = EmailFolder::getByBoxAndType($emailMessage->folder->emailBox, EmailFolder::TYPE_OUTBOX_ERROR);
     $emailMessage->error = $emailMessageSendError;
     $saved = $emailMessage->save();
     $this->assertTrue($saved);
     $this->assertEquals(1, EmailMessageSendError::getCount());
     //Now swap the error with a new one
     $emailMessageId = $emailMessage->id;
     $emailMessage->forget();
     $emailMessage = EmailMessage::getById($emailMessageId);
     $emailMessageSendError = new EmailMessageSendError();
     $data = array();
     $data['message'] = 'error message 2';
     $emailMessageSendError->serializedData = serialize($data);
     $emailMessage->error = $emailMessageSendError;
     $saved = $emailMessage->save();
     $this->assertTrue($saved);
     $this->assertEquals(1, EmailMessageSendError::getCount());
 }
 public static function setUpBeforeClass()
 {
     parent::setUpBeforeClass();
     $user = SecurityTestHelper::createSuperAdmin();
     Yii::app()->user->userModel = $user;
     $user = new User();
     $user->username = '******';
     $user->firstName = 'James';
     $user->lastName = 'Boondog';
     assert($user->save());
     // Not Coding Standard
     BaseControlUserConfigUtil::getUserToRunAs();
     assert(AuditEvent::getCount() == 10);
     // Not Coding Standard
     ContactsModule::loadStartingData();
     Yii::app()->gameHelper->muteScoringModelsOnSave();
 }
Exemple #7
0
 /**
  * A notification email is different than a regular outbound email because it is owned by a super user
  * that is different than the user logged in.  So the sender does not have a 'person'
  */
 public function testCreateEmailMessageThatIsANotification()
 {
     $super = User::getByUsername('super');
     Yii::app()->user->userModel = $super;
     $billy = User::getByUsername('billy');
     $this->assertEquals(0, count(EmailMessage::getAll()));
     $emailMessage = new EmailMessage();
     $emailMessage->owner = BaseControlUserConfigUtil::getUserToRunAs();
     $emailMessage->subject = 'My First Email';
     //Attempt to save without setting required information
     $saved = $emailMessage->save();
     $this->assertFalse($saved);
     $compareData = array('folder' => array('name' => array('Name cannot be blank.'), 'emailBox' => array('name' => array('Name cannot be blank.'))), 'sender' => array('fromAddress' => array('From Address cannot be blank.')));
     $this->assertEquals($compareData, $emailMessage->getErrors());
     //Set sender, and recipient, and content
     $emailContent = new EmailMessageContent();
     $emailContent->textContent = 'My First Message';
     $emailContent->htmlContent = 'Some fake HTML content';
     $emailMessage->content = $emailContent;
     //Sending from the system, does not have a 'person'.
     $sender = new EmailMessageSender();
     $sender->fromAddress = '*****@*****.**';
     $sender->fromName = 'Zurmo System';
     $emailMessage->sender = $sender;
     //Recipient is billy.
     $recipient = new EmailMessageRecipient();
     $recipient->toAddress = '*****@*****.**';
     $recipient->toName = 'Billy James';
     $recipient->type = EmailMessageRecipient::TYPE_TO;
     $recipient->personOrAccount = $billy;
     $emailMessage->recipients->add($recipient);
     //At this point the message is in no folder
     $this->assertTrue($emailMessage->folder->id < 0);
     $box = EmailBox::resolveAndGetByName(EmailBox::NOTIFICATIONS_NAME);
     $emailMessage->folder = EmailFolder::getByBoxAndType($box, EmailFolder::TYPE_DRAFT);
     //Save, at this point the email should be in the draft folder
     $saved = $emailMessage->save();
     $this->assertTrue($saved);
     $this->assertTrue($emailMessage->folder->id > 0);
     //At this point the message should be in the draft folder by default.
     $this->assertEquals(EmailFolder::getDefaultDraftName(), $emailMessage->folder->name);
     $this->assertEquals(EmailFolder::TYPE_DRAFT, $emailMessage->folder->type);
 }
 /**
  *
  * (non-PHPdoc)
  * @see BaseJob::run()
  */
 public function run()
 {
     $messageContent = null;
     $userToSendMessagesFrom = BaseControlUserConfigUtil::getUserToRunAs();
     $from = array('name' => Yii::app()->emailHelper->resolveFromNameForSystemUser($userToSendMessagesFrom), 'address' => Yii::app()->emailHelper->resolveFromAddressByUser($userToSendMessagesFrom));
     $emailMessage = EmailMessageHelper::processAndCreateTestEmailMessage($from, Yii::app()->emailHelper->defaultTestToAddress);
     $validatedAndSaved = $emailMessage->save();
     if (!$validatedAndSaved) {
         throw new NotSupportedException();
     }
     Yii::app()->emailHelper->sendImmediately($emailMessage);
     if (!$emailMessage->hasSendError()) {
         $messageContent .= Zurmo::t('EmailMessagesModule', 'Message successfully sent') . "\n";
         return true;
     } else {
         $messageContent .= Zurmo::t('EmailMessagesModule', 'Message failed to send') . "\n";
         $messageContent .= $emailMessage->error . "\n";
         $this->errorMessage = $messageContent;
         return false;
     }
 }
 /**
  * @see BaseJob::run()
  */
 public function run()
 {
     try {
         $originalUser = Yii::app()->user->userModel;
         Yii::app()->user->userModel = BaseControlUserConfigUtil::getUserToRunAs();
         foreach (ByTimeWorkflowInQueue::getModelsToProcess(self::$pageSize) as $byTimeWorkflowInQueue) {
             try {
                 $model = $this->resolveModel($byTimeWorkflowInQueue);
                 $this->resolveSavedWorkflowIsValid($byTimeWorkflowInQueue);
                 $this->processByTimeWorkflowInQueue($byTimeWorkflowInQueue, $model);
             } catch (NotFoundException $e) {
                 WorkflowUtil::handleProcessingException($e, 'application.modules.workflows.jobs.ByTimeWorkflowInQueueJob.run');
             }
             $byTimeWorkflowInQueue->delete();
         }
         Yii::app()->user->userModel = $originalUser;
         return true;
     } catch (MissingASuperAdministratorException $e) {
         //skip running workflow, since no super administrators are available.
         $this->errorMessage = Zurmo::t('WorkflowsModule', 'Could not process since no super administrators were found');
         return false;
     }
 }
 /**
  * Send system email message
  * @param string $subject
  * @param array $recipients
  * @param string $textContent
  * @param string $htmlContent
  * @throws NotSupportedException
  */
 public static function sendSystemEmail($subject, $recipients, $textContent = '', $htmlContent = '')
 {
     $emailMessage = new EmailMessage();
     $emailMessage->owner = BaseControlUserConfigUtil::getUserToRunAs();
     $emailMessage->subject = $subject;
     $emailContent = new EmailMessageContent();
     $emailContent->textContent = $textContent;
     $emailContent->htmlContent = $htmlContent;
     $emailMessage->content = $emailContent;
     $sender = new EmailMessageSender();
     $sender->fromAddress = Yii::app()->emailHelper->resolveFromAddressByUser(Yii::app()->user->userModel);
     $sender->fromName = strval(Yii::app()->user->userModel);
     $sender->personsOrAccounts->add(Yii::app()->user->userModel);
     $emailMessage->sender = $sender;
     foreach ($recipients as $recipientEmail) {
         $recipient = new EmailMessageRecipient();
         $recipient->toAddress = $recipientEmail;
         $recipient->type = EmailMessageRecipient::TYPE_TO;
         $emailMessage->recipients->add($recipient);
     }
     $box = EmailBox::resolveAndGetByName(EmailBox::NOTIFICATIONS_NAME);
     $emailMessage->folder = EmailFolder::getByBoxAndType($box, EmailFolder::TYPE_DRAFT);
     $validated = $emailMessage->validate();
     if (!$validated) {
         throw new NotSupportedException();
     }
     Yii::app()->emailHelper->sendImmediately($emailMessage);
     $saved = $emailMessage->save();
     if (!$saved) {
         throw new NotSupportedException();
     }
     if (!$emailMessage->hasSendError()) {
         return true;
     } else {
         return false;
     }
 }
 /**
  *
  * (non-PHPdoc)
  * @see BaseJob::run()
  */
 public function run()
 {
     $messageContent = null;
     $userToSendMessagesFrom = BaseControlUserConfigUtil::getUserToRunAs();
     $emailMessage = new EmailMessage();
     $emailMessage->owner = Yii::app()->user->userModel;
     $emailMessage->subject = Zurmo::t('EmailMessagesModule', 'A test email from Zurmo', LabelUtil::getTranslationParamsForAllModules());
     $emailContent = new EmailMessageContent();
     $emailContent->textContent = Zurmo::t('EmailMessagesModule', 'A test text message from Zurmo.', LabelUtil::getTranslationParamsForAllModules());
     $emailContent->htmlContent = Zurmo::t('EmailMessagesModule', 'A test text message from Zurmo.', LabelUtil::getTranslationParamsForAllModules());
     $emailMessage->content = $emailContent;
     $sender = new EmailMessageSender();
     $sender->fromAddress = Yii::app()->emailHelper->resolveFromAddressByUser($userToSendMessagesFrom);
     $sender->fromName = Yii::app()->emailHelper->resolveFromNameForSystemUser($userToSendMessagesFrom);
     $emailMessage->sender = $sender;
     $recipient = new EmailMessageRecipient();
     $recipient->toAddress = Yii::app()->emailHelper->defaultTestToAddress;
     $recipient->toName = 'Test Recipient';
     $recipient->type = EmailMessageRecipient::TYPE_TO;
     $emailMessage->recipients->add($recipient);
     $box = EmailBox::resolveAndGetByName(EmailBox::NOTIFICATIONS_NAME);
     $emailMessage->folder = EmailFolder::getByBoxAndType($box, EmailFolder::TYPE_DRAFT);
     $validatedAndSaved = $emailMessage->save();
     if (!$validatedAndSaved) {
         throw new NotSupportedException();
     }
     Yii::app()->emailHelper->sendImmediately($emailMessage);
     if (!$emailMessage->hasSendError()) {
         $messageContent .= Zurmo::t('EmailMessagesModule', 'Message successfully sent') . "\n";
         return true;
     } else {
         $messageContent .= Zurmo::t('EmailMessagesModule', 'Message failed to send') . "\n";
         $messageContent .= $emailMessage->error . "\n";
         $this->errorMessage = $messageContent;
         return false;
     }
 }
Exemple #12
0
 public function actionTrack()
 {
     try {
         Yii::app()->user->userModel = BaseControlUserConfigUtil::getUserToRunAs();
         $response = EmailMessageActivityUtil::resolveQueryStringFromUrlAndCreateOrUpdateActivity();
         if ($response['redirect']) {
             $this->redirect($response['url']);
         } elseif (isset($response['imagePath'])) {
             $mime = ZurmoFileHelper::getMimeType($response['imagePath']);
             $size = filesize($response['imagePath']);
             $name = pathinfo($response['imagePath'], PATHINFO_FILENAME);
             header('Content-Type: ' . $mime);
             header('Content-Length: ' . $size);
             header('Content-Name: ' . $name);
             readfile($response['imagePath']);
             Yii::app()->end(0, false);
         }
     } catch (NotFoundException $e) {
     } catch (NotSupportedException $e) {
     } catch (FailedToSaveModelException $e) {
     } catch (MissingASuperAdministratorException $e) {
     }
     // we do not catch all exceptions because we need Exit and Redirect Exception for unit tests
 }
 /**
  * Send Test Message
  * @param SendGridWebApiConfigurationForm $configurationForm
  * @param string $fromNameToSendMessagesFrom
  * @param string $fromAddressToSendMessagesFrom
  */
 public static function sendTestMessage($configurationForm, $fromNameToSendMessagesFrom = null, $fromAddressToSendMessagesFrom = null)
 {
     if ($configurationForm->aTestToAddress != null) {
         $sendGridEmailAccount = new SendGridEmailAccount();
         $sendGridEmailAccount->apiUsername = $configurationForm->username;
         $sendGridEmailAccount->apiPassword = ZurmoPasswordSecurityUtil::encrypt($configurationForm->password);
         $isUser = false;
         if ($fromNameToSendMessagesFrom != null && $fromAddressToSendMessagesFrom != null) {
             $isUser = true;
             $from = array('name' => $fromNameToSendMessagesFrom, 'address' => $fromAddressToSendMessagesFrom);
         } else {
             $user = BaseControlUserConfigUtil::getUserToRunAs();
             $userToSendMessagesFrom = User::getById((int) $user->id);
             $from = array('name' => Yii::app()->emailHelper->resolveFromNameForSystemUser($userToSendMessagesFrom), 'address' => Yii::app()->emailHelper->resolveFromAddressByUser($userToSendMessagesFrom));
         }
         $emailMessage = EmailMessageHelper::processAndCreateTestEmailMessage($from, $configurationForm->aTestToAddress);
         $mailer = new ZurmoSendGridMailer($emailMessage, $sendGridEmailAccount);
         $emailMessage = $mailer->sendTestEmail($isUser);
         $messageContent = EmailHelper::prepareMessageContent($emailMessage);
     } else {
         $messageContent = Zurmo::t('EmailMessagesModule', 'A test email address must be entered before you can send a test email.') . "\n";
     }
     return $messageContent;
 }
 /**
  * @return EmailMessageSender
  */
 protected static function makeSender()
 {
     $userToSendMessagesFrom = BaseControlUserConfigUtil::getUserToRunAs();
     $sender = new EmailMessageSender();
     $sender->fromAddress = Yii::app()->emailHelper->resolveFromAddressByUser($userToSendMessagesFrom);
     $sender->fromName = strval($userToSendMessagesFrom);
     return $sender;
 }
 /**
  * @return EmailMessageSender
  * @throws NotSupportedException
  */
 protected function resolveSender()
 {
     $sender = new EmailMessageSender();
     if ($this->emailMessageForm->sendFromType == EmailMessageForWorkflowForm::SEND_FROM_TYPE_DEFAULT) {
         $userToSendMessagesFrom = BaseControlUserConfigUtil::getUserToRunAs();
         $sender->fromAddress = Yii::app()->emailHelper->resolveFromAddressByUser($userToSendMessagesFrom);
         $sender->fromName = strval($userToSendMessagesFrom);
     } elseif ($this->emailMessageForm->sendFromType == EmailMessageForWorkflowForm::SEND_FROM_TYPE_CUSTOM) {
         $sender->fromAddress = $this->emailMessageForm->sendFromAddress;
         $sender->fromName = $this->emailMessageForm->sendFromName;
     } else {
         throw new NotSupportedException();
     }
     return $sender;
 }
 /**
  * Given a event, process any workflow rules
  * @param CEvent $event
  */
 public function processWorkflowAfterSave(CEvent $event)
 {
     $model = $event->sender;
     if ($this->depth < 11 && $model->shouldProcessWorkflowOnSave()) {
         try {
             $this->depth = $this->depth + 1;
             $triggeredByUser = Yii::app()->user->userModel;
             Yii::app()->user->userModel = BaseControlUserConfigUtil::getUserToRunAs();
             $model->setDoNotProcessWorkflowOnSave();
             SavedWorkflowsUtil::resolveAfterSaveByModel($model, $triggeredByUser);
             $model->setProcessWorkflowOnSave();
             Yii::app()->user->userModel = $triggeredByUser;
         } catch (MissingASuperAdministratorException $e) {
             //skip running workflow, since no super administrators are available.
         }
         $this->depth = $this->depth - 1;
     } elseif ($this->depth > 10) {
         $message = new NotificationMessage();
         $message->htmlContent = Zurmo::t('WorkflowsModule', 'The combination of workflow rules setup caused ' . 'an infinite loop and processing was stopped prematurely while saving the ' . 'following record: {modelName}', array('{modelName}' => strval($model)));
         $url = Yii::app()->createAbsoluteUrl('workflows/default/list');
         $message->htmlContent .= "<br/>" . ZurmoHtml::link(Zurmo::t('WorkflowsModule', 'Manage Workflows'), $url);
         $rules = new WorkflowMaximumDepthNotificationRules();
         NotificationsUtil::submit($message, $rules);
     }
 }
 protected function resolveSenderAsDefault(EmailMessageSender $sender)
 {
     $userToSendMessagesFrom = BaseControlUserConfigUtil::getUserToRunAs();
     $sender->fromAddress = Yii::app()->emailHelper->resolveFromAddressByUser($userToSendMessagesFrom);
     $sender->fromName = strval($userToSendMessagesFrom);
 }
 protected static function sendEmail(Notification $notification)
 {
     if ($notification->owner->primaryEmail->emailAddress !== null && !UserConfigurationFormAdapter::resolveAndGetValue($notification->owner, 'turnOffEmailNotifications')) {
         $userToSendMessagesFrom = BaseControlUserConfigUtil::getUserToRunAs();
         $emailMessage = new EmailMessage();
         $emailMessage->owner = Yii::app()->user->userModel;
         $emailMessage->subject = strval($notification);
         $emailContent = new EmailMessageContent();
         $emailContent->textContent = EmailNotificationUtil::resolveNotificationTextTemplate($notification->notificationMessage->textContent);
         $emailContent->htmlContent = EmailNotificationUtil::resolveNotificationHtmlTemplate($notification->notificationMessage->htmlContent);
         $emailMessage->content = $emailContent;
         $sender = new EmailMessageSender();
         $sender->fromAddress = Yii::app()->emailHelper->resolveFromAddressByUser($userToSendMessagesFrom);
         $sender->fromName = strval($userToSendMessagesFrom);
         $emailMessage->sender = $sender;
         $recipient = new EmailMessageRecipient();
         $recipient->toAddress = $notification->owner->primaryEmail->emailAddress;
         $recipient->toName = strval($notification->owner);
         $recipient->type = EmailMessageRecipient::TYPE_TO;
         $recipient->personsOrAccounts->add($notification->owner);
         $emailMessage->recipients->add($recipient);
         $box = EmailBox::resolveAndGetByName(EmailBox::NOTIFICATIONS_NAME);
         $emailMessage->folder = EmailFolder::getByBoxAndType($box, EmailFolder::TYPE_DRAFT);
         if (!$emailMessage->save()) {
             throw new FailedToSaveModelException();
         }
         try {
             Yii::app()->emailHelper->sendImmediately($emailMessage);
         } catch (CException $e) {
             //Not sure what to do yet when catching an exception here. Currently ignoring gracefully.
         }
     }
 }
 /**
  * Assumes before calling this, the outbound settings have been validated in the form.
  * Todo: When new user interface is complete, this will be re-worked to be on page instead of modal.
  */
 public function actionSendTestMessage()
 {
     $configurationForm = EmailSmtpConfigurationFormAdapter::makeFormFromGlobalConfiguration();
     $postVariableName = get_class($configurationForm);
     if (isset($_POST[$postVariableName]) || isset($_POST['UserEmailConfigurationForm'])) {
         if (isset($_POST[$postVariableName])) {
             $configurationForm->setAttributes($_POST[$postVariableName]);
         } else {
             //Check for sendgrid
             if ($_POST['UserEmailConfigurationForm']['useCustomOutboundSettings'] == EmailMessageUtil::OUTBOUND_PERSONAL_SENDGRID_SETTINGS) {
                 $this->processSendTestMessageForSendGrid();
             } else {
                 $configurationForm->host = $_POST['UserEmailConfigurationForm']['outboundHost'];
                 $configurationForm->port = $_POST['UserEmailConfigurationForm']['outboundPort'];
                 $configurationForm->username = $_POST['UserEmailConfigurationForm']['outboundUsername'];
                 $configurationForm->password = $_POST['UserEmailConfigurationForm']['outboundPassword'];
                 $configurationForm->security = $_POST['UserEmailConfigurationForm']['outboundSecurity'];
                 $configurationForm->aTestToAddress = $_POST['UserEmailConfigurationForm']['aTestToAddress'];
                 $fromNameToSendMessagesFrom = $_POST['UserEmailConfigurationForm']['fromName'];
                 $fromAddressToSendMessagesFrom = $_POST['UserEmailConfigurationForm']['fromAddress'];
             }
         }
         if ($configurationForm->aTestToAddress != null) {
             $emailAccount = new EmailAccount();
             $emailAccount->outboundHost = $configurationForm->host;
             $emailAccount->outboundPort = $configurationForm->port;
             $emailAccount->outboundUsername = $configurationForm->username;
             $emailAccount->outboundPassword = ZurmoPasswordSecurityUtil::encrypt($configurationForm->password);
             $emailAccount->outboundSecurity = $configurationForm->security;
             $isUser = false;
             if (isset($fromNameToSendMessagesFrom) && isset($fromAddressToSendMessagesFrom)) {
                 $isUser = true;
                 $from = array('name' => $fromNameToSendMessagesFrom, 'address' => $fromAddressToSendMessagesFrom);
             } else {
                 $user = BaseControlUserConfigUtil::getUserToRunAs();
                 $userToSendMessagesFrom = User::getById((int) $user->id);
                 $from = array('name' => Yii::app()->emailHelper->resolveFromNameForSystemUser($userToSendMessagesFrom), 'address' => Yii::app()->emailHelper->resolveFromAddressByUser($userToSendMessagesFrom));
             }
             $emailMessage = EmailMessageHelper::processAndCreateEmailMessage($from, $configurationForm->aTestToAddress);
             $mailer = new ZurmoSwiftMailer($emailMessage, $emailAccount);
             $emailMessage = $mailer->sendTestEmail($isUser);
             $messageContent = EmailHelper::prepareMessageContent($emailMessage);
         } else {
             $messageContent = Zurmo::t('EmailMessagesModule', 'A test email address must be entered before you can send a test email.') . "\n";
         }
         Yii::app()->getClientScript()->setToAjaxMode();
         $messageView = new TestConnectionView($messageContent);
         $view = new ModalView($this, $messageView);
         echo $view->render();
     } else {
         throw new NotSupportedException();
     }
 }
 /**
  * Assumes before calling this, the outbound settings have been validated in the form.
  * Todo: When new user interface is complete, this will be re-worked to be on page instead of modal.
  */
 public function actionSendTestMessage()
 {
     $configurationForm = EmailSmtpConfigurationFormAdapter::makeFormFromGlobalConfiguration();
     $postVariableName = get_class($configurationForm);
     if (isset($_POST[$postVariableName]) || isset($_POST['UserEmailConfigurationForm'])) {
         if (isset($_POST[$postVariableName])) {
             $configurationForm->setAttributes($_POST[$postVariableName]);
         } else {
             $configurationForm->host = $_POST['UserEmailConfigurationForm']['outboundHost'];
             $configurationForm->port = $_POST['UserEmailConfigurationForm']['outboundPort'];
             $configurationForm->username = $_POST['UserEmailConfigurationForm']['outboundUsername'];
             $configurationForm->password = $_POST['UserEmailConfigurationForm']['outboundPassword'];
             $configurationForm->security = $_POST['UserEmailConfigurationForm']['outboundSecurity'];
             $configurationForm->aTestToAddress = $_POST['UserEmailConfigurationForm']['aTestToAddress'];
             $fromNameToSendMessagesFrom = $_POST['UserEmailConfigurationForm']['fromName'];
             $fromAddressToSendMessagesFrom = $_POST['UserEmailConfigurationForm']['fromAddress'];
         }
         if ($configurationForm->aTestToAddress != null) {
             $emailHelper = new EmailHelper();
             $emailHelper->loadDefaultFromAndToAddresses();
             $emailHelper->outboundHost = $configurationForm->host;
             $emailHelper->outboundPort = $configurationForm->port;
             $emailHelper->outboundUsername = $configurationForm->username;
             $emailHelper->outboundPassword = $configurationForm->password;
             $emailHelper->outboundSecurity = $configurationForm->security;
             if (isset($fromNameToSendMessagesFrom) && isset($fromAddressToSendMessagesFrom)) {
                 $from = array('name' => $fromNameToSendMessagesFrom, 'address' => $fromAddressToSendMessagesFrom);
                 $emailMessage = EmailMessageHelper::sendTestEmail($emailHelper, $from, $configurationForm->aTestToAddress);
             } else {
                 $user = BaseControlUserConfigUtil::getUserToRunAs();
                 $userToSendMessagesFrom = User::getById((int) $user->id);
                 $emailMessage = EmailMessageHelper::sendTestEmailFromUser($emailHelper, $userToSendMessagesFrom, $configurationForm->aTestToAddress);
             }
             $messageContent = null;
             if (!($emailMessage->hasErrors() || $emailMessage->hasSendError())) {
                 $messageContent .= Zurmo::t('EmailMessagesModule', 'Message successfully sent') . "\n";
             } else {
                 $messageContent .= Zurmo::t('EmailMessagesModule', 'Message failed to send') . "\n";
                 if ($emailMessage->hasSendError()) {
                     $messageContent .= $emailMessage->error . "\n";
                 } else {
                     //todo: refactor to use ZurmoHtml::errorSummary after this supports that method
                     //todo: supports nested messages better.
                     $errors = $emailMessage->getErrors();
                     foreach ($errors as $attributeNameWithErrors) {
                         foreach ($attributeNameWithErrors as $attributeError) {
                             if (is_array($attributeError)) {
                                 foreach ($attributeError as $nestedAttributeError) {
                                     $messageContent .= reset($nestedAttributeError) . "\n";
                                 }
                             } else {
                                 $messageContent .= reset($attributeError) . "\n";
                             }
                         }
                     }
                 }
             }
         } else {
             $messageContent = Zurmo::t('EmailMessagesModule', 'A test email address must be entered before you can send a test email.') . "\n";
         }
         Yii::app()->getClientScript()->setToAjaxMode();
         $messageView = new TestConnectionView($messageContent);
         $view = new ModalView($this, $messageView);
         echo $view->render();
     } else {
         throw new NotSupportedException();
     }
 }
 public function beforeAction($action)
 {
     Yii::app()->user->userModel = BaseControlUserConfigUtil::getUserToRunAs();
     return parent::beforeAction($action);
 }
 /**
  * @depends testProcessDueAutoresponderItemDoesNotThrowExceptionWhenContactHasNoPrimaryEmail
  */
 public function testProcessDueAutoresponderItemDoesNotThrowExceptionWhenContactHasPrimaryEmail()
 {
     $email = new Email();
     $email->emailAddress = '*****@*****.**';
     $contact = ContactTestHelper::createContactByNameForOwner('contact 03', $this->user);
     $contact->primaryEmail = $email;
     $this->assertTrue($contact->save());
     $marketingList = MarketingListTestHelper::createMarketingListByName('marketingList 03');
     $autoresponder = AutoresponderTestHelper::createAutoresponder('subject 03', 'text content', 'html content', 1, Autoresponder::OPERATION_SUBSCRIBE, true, $marketingList);
     $processed = 0;
     $processDateTime = DateTimeUtil::convertTimestampToDbFormatDateTime(time());
     $autoresponderItem = AutoresponderItemTestHelper::createAutoresponderItem($processed, $processDateTime, $autoresponder, $contact);
     $this->processDueItem($autoresponderItem);
     $this->assertEquals(1, $autoresponderItem->processed);
     $emailMessage = $autoresponderItem->emailMessage;
     $this->assertEquals($marketingList->owner->id, $emailMessage->owner->id);
     $marketingListPermissions = ExplicitReadWriteModelPermissionsUtil::makeBySecurableItem($marketingList);
     $emailMessagePermissions = ExplicitReadWriteModelPermissionsUtil::makeBySecurableItem($emailMessage);
     $this->assertEquals($marketingListPermissions, $emailMessagePermissions);
     $this->assertEquals($autoresponder->subject, $emailMessage->subject);
     $this->assertContains($autoresponder->textContent, $emailMessage->content->textContent);
     $this->assertContains('/marketingLists/external/', $emailMessage->content->textContent);
     $this->assertEquals(2, substr_count($emailMessage->content->textContent, '/marketingLists/external/'));
     $this->assertContains($autoresponder->htmlContent, $emailMessage->content->htmlContent);
     $this->assertContains('/marketingLists/external/', $emailMessage->content->htmlContent);
     $this->assertEquals(2, substr_count($emailMessage->content->htmlContent, '/marketingLists/external/'));
     $userToSendMessagesFrom = BaseControlUserConfigUtil::getUserToRunAs();
     $defaultFromAddress = Yii::app()->emailHelper->resolveFromAddressByUser($userToSendMessagesFrom);
     $defaultFromName = strval($userToSendMessagesFrom);
     $this->assertEquals($defaultFromAddress, $emailMessage->sender->fromAddress);
     $this->assertEquals($defaultFromName, $emailMessage->sender->fromName);
     $this->assertEquals(1, $emailMessage->recipients->count());
     $recipients = $emailMessage->recipients;
     $this->assertEquals(strval($contact), $recipients[0]->toName);
     $this->assertEquals($email->emailAddress, $recipients[0]->toAddress);
     $this->assertEquals(EmailMessageRecipient::TYPE_TO, $recipients[0]->type);
     $this->assertTrue($contact->isSame($recipients[0]->personsOrAccounts[0]));
     $headersArray = array('zurmoItemId' => $autoresponderItem->id, 'zurmoItemClass' => get_class($autoresponderItem), 'zurmoPersonId' => $contact->getClassId('Person'));
     $expectedHeaders = serialize($headersArray);
     $this->assertEquals($expectedHeaders, $emailMessage->headers);
 }
 protected static function resolveSender(MarketingList $marketingList, $itemOwnerModel)
 {
     $sender = new EmailMessageSender();
     if (get_class($itemOwnerModel) == 'Campaign') {
         $sender->fromAddress = $itemOwnerModel->fromAddress;
         $sender->fromName = $itemOwnerModel->fromName;
         return $sender;
     }
     if (!empty($marketingList->fromName) && !empty($marketingList->fromAddress)) {
         $sender->fromAddress = $marketingList->fromAddress;
         $sender->fromName = $marketingList->fromName;
     } else {
         $userToSendMessagesFrom = BaseControlUserConfigUtil::getUserToRunAs();
         $sender->fromAddress = Yii::app()->emailHelper->resolveFromAddressByUser($userToSendMessagesFrom);
         $sender->fromName = strval($userToSendMessagesFrom);
     }
     return $sender;
 }
 /**
  * Execute the action.
  * @param array command line parameters specific for this command
  */
 public function actionSend($username, $toAddress, $subject = 'A test email from Zurmo', $textContent = 'A test text message from Zurmo.', $htmlContent = 'A test html message from Zurmo.', $host = null, $port = null, $outboundUsername = null, $outboundPassword = null, $outboundSecurity = null)
 {
     if (!isset($username)) {
         $this->usageError('A username must be specified.');
     }
     if (!isset($toAddress)) {
         $this->usageError('You must specify a to address.');
     }
     try {
         Yii::app()->user->userModel = User::getByUsername($username);
     } catch (NotFoundException $e) {
         $this->usageError('The specified username does not exist.');
     }
     $this->setEmailHelperSettings($host, $port, $outboundUsername, $outboundPassword, $outboundSecurity);
     echo "\n";
     echo 'Using type:' . Yii::app()->emailHelper->outboundType . "\n";
     echo 'Using host:' . Yii::app()->emailHelper->outboundHost . "\n";
     echo 'Using port:' . Yii::app()->emailHelper->outboundPort . "\n";
     echo 'Using username:'******'Using password:'******'Using outbound security:' . Yii::app()->emailHelper->outboundSecurity . "\n\n";
     } else {
         echo 'Using outbound security: none' . "\n\n";
     }
     echo 'Sending Email Message' . "\n";
     $emailMessage = new EmailMessage();
     $emailMessage->owner = BaseControlUserConfigUtil::getUserToRunAs();
     $emailMessage->subject = $subject;
     $emailContent = new EmailMessageContent();
     $emailContent->textContent = $textContent;
     $emailContent->htmlContent = $htmlContent;
     $emailMessage->content = $emailContent;
     $sender = new EmailMessageSender();
     $sender->fromAddress = Yii::app()->emailHelper->resolveFromAddressByUser(Yii::app()->user->userModel);
     $sender->fromName = strval(Yii::app()->user->userModel);
     $sender->personsOrAccounts->add(Yii::app()->user->userModel);
     $emailMessage->sender = $sender;
     $recipient = new EmailMessageRecipient();
     $recipient->toAddress = $toAddress;
     $recipient->toName = 'Test Recipient';
     $recipient->type = EmailMessageRecipient::TYPE_TO;
     $emailMessage->recipients->add($recipient);
     $box = EmailBox::resolveAndGetByName(EmailBox::NOTIFICATIONS_NAME);
     $emailMessage->folder = EmailFolder::getByBoxAndType($box, EmailFolder::TYPE_DRAFT);
     $validated = $emailMessage->validate();
     if (!$validated) {
         $this->addErrorsAsUsageErrors($emailMessage->getErrors());
     }
     Yii::app()->emailHelper->sendImmediately($emailMessage);
     if (!$emailMessage->hasSendError()) {
         echo Zurmo::t('EmailMessagesModule', 'Message successfully sent') . "\n";
     } else {
         echo Zurmo::t('EmailMessagesModule', 'Message failed to send') . "\n";
         echo $emailMessage->error . "\n";
     }
     $saved = $emailMessage->save();
     if (!$saved) {
         throw new NotSupportedException();
     }
 }
 protected static function resolveSender(MarketingList $marketingList, $itemOwnerModel)
 {
     if (get_class($itemOwnerModel) == 'Campaign') {
         $fromAddress = $itemOwnerModel->fromAddress;
         $fromName = $itemOwnerModel->fromName;
     } else {
         if (!empty($marketingList->fromName) && !empty($marketingList->fromAddress)) {
             $fromAddress = $marketingList->fromAddress;
             $fromName = $marketingList->fromName;
         } else {
             $userToSendMessagesFrom = BaseControlUserConfigUtil::getUserToRunAs();
             $fromAddress = Yii::app()->emailHelper->resolveFromAddressByUser($userToSendMessagesFrom);
             $fromName = Yii::app()->emailHelper->resolveFromNameForSystemUser($userToSendMessagesFrom);
         }
     }
     $sender = compact('fromName', 'fromAddress');
     return $sender;
 }