/**
  * Hook that allows actions when the form is submitted, but it was not the submit button that was checked
  *
  * When not rerouted, the form will be populated afterwards
  */
 protected function onFakeSubmit()
 {
     if (isset($this->formData['create_account']) && $this->formData['create_account']) {
         $mail = $this->loader->getMailLoader()->getMailer('staffPassword', $this->user->getUserId());
         $mail->setOrganizationFrom();
         if ($mail->setCreateAccountTemplate()) {
             $mail->send();
             $this->addMessage($this->_('Create account mail sent'));
             $this->setAfterSaveRoute();
         } else {
             $this->addMessage($this->_('No default Create Account mail template set in organization or project'));
         }
         return;
     }
     if (isset($this->formData['reset_password']) && $this->formData['reset_password']) {
         $mail = $this->loader->getMailLoader()->getMailer('staffPassword', $this->user->getUserId());
         $mail->setOrganizationFrom();
         if ($mail->setResetPasswordTemplate()) {
             $mail->send();
             $this->addMessage($this->_('Reset password mail sent'));
             $this->setAfterSaveRoute();
         } else {
             $this->addMessage($this->_('No default Reset Password mail template set in organization or project'));
         }
     }
 }
 /**
  * Loads the correct mailer
  */
 protected function loadMailer()
 {
     $this->mailTarget = false;
     if (isset($this->formData['gct_target']) && isset($this->mailTargets[$this->formData['gct_target']])) {
         $this->mailTarget = $this->formData['gct_target'];
     } else {
         reset($this->mailTargets);
         $this->mailTarget = key($this->mailTargets);
     }
     $this->mailer = $this->loader->getMailLoader()->getMailer($this->mailTarget);
 }
 /**
  * Helper function to get the templates for mails
  *
  * @param string|array $for the template types to get
  * @return array
  */
 public function getPasswordTemplatesFor($for)
 {
     return $this->loader->getMailLoader()->getMailElements()->getAvailableMailTemplates(false, $for);
 }
 /**
  *
  * @param array $job
  */
 public function execute($jobId = null)
 {
     $sql = $this->db->select()->from('gems__comm_jobs')->join('gems__comm_templates', 'gcj_id_message = gct_id_template')->where('gcj_active = 1')->where('gcj_id_job = ?', $jobId);
     $job = $this->db->fetchRow($sql);
     if (empty($job)) {
         throw new Exception($this->_('Mail job not found!'));
     }
     $dbLookup = $this->loader->getUtil()->getDbLookup();
     $mailLoader = $this->loader->getMailLoader();
     $sendByMail = $this->getUserEmail($job['gcj_id_user_as']);
     $filter = $dbLookup->getFilterForMailJob($job);
     $tracker = $this->loader->getTracker();
     $model = $tracker->getTokenModel();
     // Fix for #680: token with the valid from the longest in the past should be the
     // used as first token and when multiple rounds start at the same date the
     // lowest round order should be used.
     $model->setSort(array('gto_valid_from' => SORT_ASC, 'gto_round_order' => SORT_ASC));
     $multipleTokensData = $model->load($filter);
     $errors = 0;
     $mails = 0;
     $updates = 0;
     if (count($multipleTokensData)) {
         $sentMailAddresses = array();
         foreach ($multipleTokensData as $tokenData) {
             $mailer = $mailLoader->getMailer('token', $tokenData);
             /* @var $mailer \Gems_Mail_TokenMailer */
             $token = $mailer->getToken();
             $email = $token->getEmail();
             $respondentId = $token->getRespondent()->getId();
             $mail = false;
             $update = false;
             if (!empty($email)) {
                 // Set the from address to use in this job
                 switch ($job['gcj_from_method']) {
                     case 'O':
                         // Send on behalf of organization
                         $organization = $mailer->getOrganization();
                         $from = $organization->getEmail();
                         //$organization->getName() . ' <' . $organization->getEmail() . '>';
                         break;
                     case 'U':
                         // Send on behalf of fixed user
                         $from = $sendByMail;
                         break;
                     case 'F':
                         // Send on behalf of fixed email address
                         $from = $job['gcj_from_fixed'];
                         break;
                     default:
                         throw new \Gems_Exception(sprintf($this->_('Invalid option for `%s`'), $this->_('From address used')));
                 }
                 $mailer->setFrom($from);
                 $mailer->setBy($sendByMail);
                 try {
                     switch ($job['gcj_process_method']) {
                         case 'M':
                             // Each token sends an email
                             $mail = true;
                             $update = true;
                             break;
                         case 'A':
                             // Only first token mailed and marked
                             if (!isset($sentMailAddresses[$respondentId][$email])) {
                                 // When not mailed before
                                 $mail = true;
                                 $update = true;
                             }
                             break;
                         case 'O':
                             // Only first token mailed, all marked
                             if (!isset($sentMailAddresses[$respondentId][$email])) {
                                 // When not mailed before
                                 $mail = true;
                             }
                             $update = true;
                             break;
                         default:
                             throw new \Gems_Exception(sprintf($this->_('Invalid option for `%s`'), $this->_('Processing Method')));
                     }
                     if ($mail == true) {
                         $mailer->setTemplate($job['gcj_id_message']);
                         $mailer->send();
                         $mails++;
                         $sentMailAddresses[$respondentId][$email] = true;
                     }
                     if ($update == true) {
                         $mailer->updateToken();
                         $updates++;
                     }
                 } catch (\Zend_Mail_Exception $exception) {
                     $fields = $mailer->getMailFields(false);
                     $info = sprintf("Error mailing to %s respondent %s with email address %s.", $fields['organization'], $fields['full_name'], $fields['email']);
                     // Use a gems exception to pass extra information to the log
                     $gemsException = new \Gems_Exception($info, 0, $exception);
                     \Gems_Log::getLogger()->logError($gemsException);
                     $errors++;
                 }
             }
         }
     }
     $this->getBatch()->addMessage(sprintf($this->_('Sent %d e-mails with template %s, updated %d tokens.'), $mails, $job['gct_name'], $updates));
     if ($errors) {
         $this->getBatch()->addMessage(sprintf($this->_('%d error(s) occurred while creating mails for template %s. Check error log for details.'), $errors, $job['gct_name']));
     }
 }
 public function afterRegistry()
 {
     $this->mailElements = $this->loader->getMailLoader()->getMailElements();
     $this->mailer = $this->loader->getMailLoader()->getMailer($this->mailTarget, $this->identifier);
     parent::afterRegistry();
 }
 /**
  * Perform automatic job mail
  */
 public function commJob()
 {
     /*
             \Zend_Mail::setDefaultTransport(new \Zend_Mail_Transport_File(array(
                 'callback' => function ($transport) {
                     // throw new \Zend_Mail_Transport_Exception('Invalid e-mail address');
                     return $transport->recipients . '_' . time() . '_' . mt_rand() . '.tmp';
                 },
                 'path'     => GEMS_ROOT_DIR . '/var/sentmails'
             )));
             // */
     $dbLookup = $this->util->getDbLookup();
     $mailLoader = $this->loader->getMailLoader();
     $tracker = $this->loader->getTracker();
     $model = $tracker->getTokenModel();
     // Fix for #680: token with the valid from the longest in the past should be the
     // used as first token and when multiple rounds start at the same date the
     // lowest round order should be used.
     $model->setSort(array('gto_valid_from' => SORT_ASC, 'gto_round_order' => SORT_ASC));
     // Check for unprocessed tokens
     $tracker->processCompletedTokens(null, $this->currentUser->getUserId());
     $sql = "SELECT *\r\n            FROM gems__comm_jobs INNER JOIN\r\n                gems__comm_templates ON gcj_id_message = gct_id_template\r\n            WHERE gcj_active = 1\r\n            ORDER BY CASE WHEN gcj_id_survey IS NULL THEN 1 ELSE 0 END,\r\n                CASE WHEN gcj_round_description IS NULL THEN 1 ELSE 0 END,\r\n                CASE WHEN gcj_id_track IS NULL THEN 1 ELSE 0 END,\r\n                CASE WHEN gcj_id_organization IS NULL THEN 1 ELSE 0 END";
     $jobs = $this->db->fetchAll($sql);
     $mailed = false;
     if ($jobs) {
         foreach ($jobs as $job) {
             $sendByMail = $this->getUserEmail($job['gcj_id_user_as']);
             $filter = $dbLookup->getFilterForMailJob($job);
             $multipleTokensData = $model->load($filter);
             if (count($multipleTokensData)) {
                 $errors = 0;
                 $mails = 0;
                 $updates = 0;
                 $sentMailAddresses = array();
                 foreach ($multipleTokensData as $tokenData) {
                     $mailer = $mailLoader->getMailer('token', $tokenData);
                     /* @var $mailer \Gems_Mail_TokenMailer */
                     $token = $mailer->getToken();
                     $email = $token->getEmail();
                     $respondentId = $token->getRespondent()->getId();
                     if (!empty($email)) {
                         if ($job['gcj_from_method'] == 'O') {
                             $organization = $mailer->getOrganization();
                             $from = $organization->getEmail();
                             //$organization->getName() . ' <' . $organization->getEmail() . '>';
                             $mailer->setFrom($from);
                         } elseif ($job['gcj_from_method'] == 'U') {
                             $from = $sendByMail;
                             $mailer->setFrom($from);
                         } elseif ($job['gcj_from_method'] == 'F') {
                             $mailer->setFrom($job['gcj_from_fixed']);
                         }
                         $mailer->setBy($sendByMail);
                         try {
                             if ($job['gcj_process_method'] == 'M') {
                                 $mailer->setTemplate($job['gcj_id_message']);
                                 $mailer->send();
                                 $mailed = true;
                                 $mails++;
                                 $updates++;
                             } elseif (!isset($sentMailAddresses[$respondentId][$email])) {
                                 $mailer->setTemplate($job['gcj_id_message']);
                                 $mailer->send();
                                 $mailed = true;
                                 $mails++;
                                 $updates++;
                                 $sentMailAddresses[$respondentId][$email] = true;
                             } elseif ($job['gcj_process_method'] == 'O') {
                                 $mailer->updateToken();
                                 $updates++;
                             }
                         } catch (\Zend_Mail_Exception $exception) {
                             $fields = $mailer->getMailFields(false);
                             $info = sprintf("Error mailing to %s respondent %s with email address %s.", $fields['organization'], $fields['full_name'], $fields['email']);
                             // Use a gems exception to pass extra information to the log
                             $gemsException = new \Gems_Exception($info, 0, $exception);
                             \Gems_Log::getLogger()->logError($gemsException);
                             $errors++;
                         }
                     }
                 }
                 $this->addMessage(sprintf($this->_('Sent %d e-mails with template %s, updated %d tokens.'), $mails, $job['gct_name'], $updates));
                 if ($errors) {
                     $this->addMessage(sprintf($this->_('%d error(s) occurred while creating mails for template %s. Check error log for details.'), $errors, $job['gct_name']));
                 }
             }
             $tokensData = null;
         }
     }
     if (!$mailed) {
         $this->addMessage($this->_('No mails sent.'));
     }
 }