public function run()
 {
     $faker = Faker::create();
     foreach (range(1, 10) as $index) {
         Email::create([]);
     }
 }
 /**
  * @param null $from
  * @param null $to
  * @param null $subject
  * @param null $body
  * @param null $bounceHandlerURL
  * @param null $cc
  * @param null $bcc
  * @return Email
  */
 public function buildEmail($from = null, $to = null, $subject = null, $body = null, $bounceHandlerURL = null, $cc = null, $bcc = null)
 {
     $env = 'dev';
     if (defined('SS_ENVIRONMENT_TYPE')) {
         $env = SS_ENVIRONMENT_TYPE;
     }
     $email = Email::create();
     if ($env == 'dev') {
         $to = defined('DEV_EMAIL_TO') ? DEV_EMAIL_TO : Config::inst()->get('Email', 'admin_email');
     }
     if (!is_null($from)) {
         $email->setFrom($from);
     }
     if (!is_null($to)) {
         $email->setTo($to);
     }
     if (!is_null($subject)) {
         $email->setSubject($subject);
     }
     if (!is_null($body)) {
         $email->setBody($body);
     }
     if (!is_null($cc)) {
         $email->setCc($cc);
     }
     if (!is_null($bcc)) {
         $email->setBcc($bcc);
     }
     return $email;
 }
 /**
  * Send verification email to member.
  */
 public function sendVerificationEmail()
 {
     $validation_link = Controller::join_links(Director::absoluteURL('Security/validate-email'), $this->owner->VerificationString);
     $site_config = SiteConfig::current_site_config();
     $site_title = $site_config->Title;
     $admin_email = Config::inst()->get('Email', 'admin_email');
     $email_template_data = array('Member' => $this->owner, 'ValidationLink' => $validation_link, 'SiteConfig' => $site_config);
     $email_subject = _t('MemberEmailVerification.VERIFICATIONEMAILSUBJECT', "{site_title} Email Verification", array('site_title' => $site_title));
     if (!$admin_email) {
         // Fallback to a placeholder admin email if Email.admin_email is not set
         $admin_email = '*****@*****.**';
     }
     $sender_email = self::get_formatted_email($site_title, $admin_email);
     $recipient_email = $this->owner->Email;
     $email_to_recipient = Email::create($sender_email, $recipient_email, $email_subject);
     $email_to_recipient->setTemplate('VerificationEmail');
     $email_to_recipient->populateTemplate($email_template_data);
     $email_status = $email_to_recipient->send();
     // Return true if the email was successfully sent
     // Mailer::email will return `true` or an array if the email was successfully sent
     if ($email_status === true || is_array($email_status)) {
         return true;
     }
     return false;
 }
Exemple #4
0
 public function create()
 {
     if ($_POST) {
         $id = $this->email->create();
         if ($id) {
             showMessage(lang('Template created', 'cmsemail'));
             if ($this->input->post('action') == 'tomain') {
                 pjax('/admin/components/cp/cmsemail/index');
             } else {
                 pjax('/admin/components/cp/cmsemail/edit/' . $id . '#settings');
             }
         } else {
             showMessage($this->email->errors, '', 'r');
         }
     } else {
         \CMSFactory\assetManager::create()->registerScript('email', TRUE)->setData('settings', $this->email->getSettings())->renderAdmin('create');
     }
 }
 public function __construct()
 {
     $this->emailer = Email::create();
     $config = $this->config();
     $this->emailer->setFrom($config->from);
     $this->emailer->setTo($config->to);
     $this->emailer->setSubject($config->subject);
     $this->emailer->setTemplate($config->template);
 }
 public function sendEmail()
 {
     $from = "The Hub Event Management <*****@*****.**>";
     $to = $this->getManagerEmail();
     $subject = "New event registration: " . $this->getTitle();
     $email = Email::create();
     $email->setFrom($from)->setTo($to)->setSubject($subject)->setTemplate('EventNotification')->populateTemplate(ArrayData::create(array('Name' => $this->Name, 'Email' => $this->Email, 'Title' => $this->getTitle(), 'StartDate' => $this->Time()->StartDate, 'StartTime' => $this->Time()->StartTime, 'EndDate' => $this->Time()->EndDate, 'EndTime' => $this->Time()->EndTime)));
     $email->send();
 }
 private function __sendEmail()
 {
     $email = Email::create();
     $email->setSenderEmailAddress($this->getSenderEmail);
     $email->setFrom($this->getFromEmail(), $this->getFromName());
     $email->setReplyToEmailAddress($this->getFromEmail());
     $email->setRecipients($this->getReceipients());
     $email->setSubject($this->getSubject());
     $email->setTextPlain($this->getBody());
     return $email->validate() && $email->send();
 }
 public function emailReport($expired, $expiring, $newMembers)
 {
     $email = Email::create();
     $to = 'secretary@nzlarps.org, treasurer@nzlarps.org';
     $email->setTo($to);
     $email->setBcc('*****@*****.**');
     $email->setSubject("NZLarps daily membership report");
     $content = $email->customise(new ArrayData(array('NewMembers' => $newMembers, 'ExpiredMembers' => $expired, 'ExpiryingMembers' => $expiring)))->renderWith('ReportEmail');
     $email->setBody($content);
     $email->send();
     echo '<p>Report has been sent</p>';
 }
 /**
  * @param string $template
  * @param string $subject
  *
  * @return Email
  */
 private function buildEmail($template, $subject)
 {
     $from = ShopConfig::config()->email_from ? ShopConfig::config()->email_from : Email::config()->admin_email;
     $to = $this->order->getLatestEmail();
     $checkoutpage = CheckoutPage::get()->first();
     $completemessage = $checkoutpage ? $checkoutpage->PurchaseComplete : '';
     $email = Email::create();
     $email->setTemplate($template);
     $email->setFrom($from);
     $email->setTo($to);
     $email->setSubject($subject);
     $email->populateTemplate(array('PurchaseCompleteMessage' => $completemessage, 'Order' => $this->order, 'BaseURL' => Director::absoluteBaseURL()));
     return $email;
 }
 /**
  *
  */
 public function onAfterWrite()
 {
     if (!$this->IsSpam) {
         /** @var Email $mail */
         $mail = Email::create();
         $to = $this->Receiver;
         $this->Target = self::$to[$this->Receiver];
         $mail->setTo($to);
         $mail->setSubject('Contact form submission ' . $this->Subject);
         $mail->setFrom($this->Email);
         $mail->setTemplate('ContactFormPost');
         $mail->populateTemplate($this);
         $mail->send();
     } else {
         $this->delete();
     }
 }
Exemple #11
0
 /**
  * Creates new marker accounts from a list of emails and sends emails to new markers.
  *
  */
 function createmarkers()
 {
     if ($this->input->post('emails')) {
         $this->load->library('validation');
         $rules['emails'] = 'valid_emails|required';
         $fields['emails'] = 'referree emails';
         $this->validation->set_fields($fields);
         $this->validation->set_rules($rules);
         $this->validation->set_message('valid_emails', 'All email addresses entered into %s must be valid, seperated by commas');
         if ($this->validation->run() === TRUE) {
             $emails = explode(',', $this->input->post('emails'));
             $this->load->model('marker');
             $this->load->model('email');
             foreach ($emails as $email) {
                 $marker = new Marker();
                 $marker->setKey($email);
                 $password = $this->_createPassword();
                 $marker->set('password', $marker->makePass($password));
                 if ($marker->create()) {
                     $emailData['email'] = $email;
                     $emailData['password'] = $password;
                     $msg = $this->load->view('email/new_marker', $emailData, TRUE);
                     $subject = 'Next step in your application';
                     $emailToStore = new Email();
                     $emailToStore->set('sender', '*****@*****.**');
                     $emailToStore->set('receiver', $email);
                     $emailToStore->set('subject', $subject);
                     $emailToStore->set('message', $msg);
                     $emailToStore->create();
                     $viewData['messages'][] = "Successfully created marker account for {$email} with password {$password}";
                 } else {
                 }
             }
         }
     }
     if ($this->validation->error_string) {
         $viewData['errors'][] = $this->validation->error_string;
     }
     $viewData['token'] = $this->_token();
     $this->load->view('control/create_markers', $viewData);
 }
 /**
  * We are abusing requireDefaultRecords to run this on dev/build.
  */
 public function requireDefaultRecords()
 {
     parent::requireDefaultRecords();
     // verbose messages
     DB::alteration_message('Searching for environment configuration for ' . Director::absoluteURL('/'), 'created');
     // get the config based on the URL (URL is key)
     $config = $this->prepConfig($this->config()->get('environments'), Director::absoluteURL('/'));
     // only run if everything is fine
     if (!is_array($config) || empty($config)) {
         DB::alteration_message('No configuration found.', 'created');
     } elseif (!file_exists('../' . $config['filename'])) {
         DB::alteration_message('No CHANGELOG.md-file found.', 'created');
     } else {
         DB::alteration_message($config['environment_name'] . ' identified.', 'created');
         // get the information in the database for the last release notification
         $record = self::get()->count() == 0 ? new self() : self::get()->first();
         // load the changelog and remove the first 4 lines
         $changelog = trim(preg_replace('/^(.*\\n){4}/', '', file_get_contents('../' . $config['filename'])));
         // check if the CHANGELOG.md file has been changed since the last run
         if ($changelog == '') {
             DB::alteration_message('No CHANGELOG found.', 'created');
         } elseif (md5($changelog) != md5($record->Changelog)) {
             // remove the former releases from the changelog
             $release = trim(str_replace($record->Changelog, '', $changelog));
             // email the changelog out
             foreach ($config['recipients'] as $recipient) {
                 Email::create($config['from'], $recipient, $config['subject'], sprintf("%s (%s)\n\n%s", $config['environment_name'], $config['url'], $release))->sendPlain();
                 DB::alteration_message($recipient . ' notified', 'created');
             }
             // save the new changelog to ensure we aren't re-running this in the next step
             $record->Changelog = $changelog;
         }
         // say welcome :)
         if (!$record->ID) {
             DB::alteration_message('Install of FriendsOfSilverStripe/release-notifications');
         }
         $record->write();
     }
 }
Exemple #13
0
 public static function email_to_img($email, $font_size = 13)
 {
     $exists = Email::where('email', '=', $email)->first();
     if (!$exists) {
         //create image
         $width = imagefontwidth($font_size) * strlen($email);
         $height = imagefontheight($font_size);
         $im = imagecreate($width, $height);
         $bg = imagecolorallocate($im, 255, 255, 255);
         $textcolor = imagecolorallocate($im, 0, 0, 0);
         imagestring($im, 5, 0, 0, $email, $textcolor);
         //get image contents
         ob_start();
         imagepng($im);
         $contents = ob_get_contents();
         ob_end_clean();
         imagedestroy($im);
         $image_code = base64_encode($contents);
         Email::create(array('email' => $email, 'image_code' => $image_code));
         return $image_code;
     }
     return $exists->image_code;
 }
 /**
  * Controller action that handles the "success" page
  * @param   $r SS_HTTPRequest
  * @return SSViewer
  */
 public function success(SS_HTTPRequest $r)
 {
     try {
         $speakers = $this->presentation->Speakers()->exclude(array('MemberID' => $this->presentation->CreatorID));
         $this->presentation->markReceived()->write();
         foreach ($speakers as $speaker) {
             $e = Email::create()->setTo($speaker->getEmail())->setUserTemplate('presentation-speaker-notification')->populateTemplate(array('RecipientMember' => $speaker->Member(), 'Presentation' => $this->presentation, 'Speaker' => $speaker, 'Creator' => $this->presentation->Creator(), 'EditLink' => Director::makeRelative($speaker->EditLink($this->presentation->ID)), 'ReviewLink' => Director::makeRelative($speaker->ReviewLink($this->presentation->ID)), 'PasswordLink' => Director::absoluteBaseURL() . '/lostpassword', 'Link' => Director::absoluteBaseURL() . Director::makeRelative($this->presentation->EditLink())))->send();
         }
         // Email the creator
         Email::create()->setTo($this->presentation->Creator()->Email)->setUserTemplate('presentation-creator-notification')->populateTemplate(array('Creator' => $this->presentation->Creator(), 'Summit' => $this->presentation->Summit(), 'Link' => Director::absoluteBaseURL() . Director::makeRelative($this->presentation->EditLink()), 'PasswordLink' => Director::absoluteBaseURL() . '/lostpassword'))->send();
         return $this->renderWith(array('PresentationPage_success', 'PresentationPage'), $this->parent);
     } catch (EntityValidationException $ex1) {
         SS_Log::log($ex1->getMessage(), SS_Log::ERR);
         Form::messageForForm('PresentationForm_PresentationForm', $ex1->getMessages(), 'bad');
         return Controller::curr()->redirect($this->presentation->EditLink());
     } catch (Exception $ex) {
         SS_Log::log($ex->getMessage(), SS_Log::ERR);
         return $this->httpError(404);
     }
 }
Exemple #15
0
if ($_REQUEST['id'] && !($email = Email::lookup($_REQUEST['id']))) {
    $errors['err'] = sprintf(__('%s: Unknown or invalid ID.'), __('email'));
}
if ($_POST) {
    switch (strtolower($_POST['do'])) {
        case 'update':
            if (!$email) {
                $errors['err'] = sprintf(__('%s: Unknown or invalid'), __('email'));
            } elseif ($email->update($_POST, $errors)) {
                $msg = sprintf(__('Successfully updated %s'), __('this email'));
            } elseif (!$errors['err']) {
                $errors['err'] = sprintf(__('Error updating %s. Try again!'), __('this email'));
            }
            break;
        case 'create':
            if ($id = Email::create($_POST, $errors)) {
                $msg = sprintf(__('Successfully added %s'), Format::htmlchars($_POST['name']));
                $_REQUEST['a'] = null;
            } elseif (!$errors['err']) {
                $errors['err'] = sprintf(__('Unable to add %s. Correct error(s) below and try again.'), __('this email'));
            }
            break;
        case 'mass_process':
            if (!$_POST['ids'] || !is_array($_POST['ids']) || !count($_POST['ids'])) {
                $errors['err'] = sprintf(__('You must select at least %s'), __('one email'));
            } else {
                $count = count($_POST['ids']);
                $sql = 'SELECT count(dept_id) FROM ' . DEPT_TABLE . ' dept ' . ' WHERE email_id IN (' . implode(',', db_input($_POST['ids'])) . ') ' . ' OR autoresp_email_id IN (' . implode(',', db_input($_POST['ids'])) . ')';
                list($depts) = db_fetch_row(db_query($sql));
                if ($depts > 0) {
                    $errors['err'] = __('One or more of the selected emails is being used by a department. Remove association first!');
 private function __sendEmail()
 {
     $emailUnban = ABF::instance()->getConfigVal(ABF::SETTING_AUTO_UNBAN);
     if ($emailUnban != 'on') {
         // do nothing
         $this->_email_sent = null;
         return;
     }
     $author = Symphony::Database()->fetchRow(0, "SELECT `id`, `email`, `first_name` FROM `tbl_authors` WHERE `email` = '" . MySQL::cleanValue($_POST['email']) . "'");
     $failure = ABF::instance()->getFailureByIp();
     $emailSettings = ABF::instance()->getEmailSettings();
     if (is_array($author) && isset($author['email']) && is_array($failure) && isset($failure[0]) && isset($failure[0]->Hash)) {
         // safe run
         try {
             // use default values
             $email = Email::create();
             // if no default values are set
             if (!is_array($emailSettings) || empty($emailSettings['from_address'])) {
                 $email->setFrom($author['email'], Symphony::Configuration()->get('sitename', 'general'));
             } else {
                 $email->setFrom($emailSettings['from_address'], $emailSettings['from_name']);
             }
             $email->recipients = $author['email'];
             $email->subject = __('Unban IP link');
             $email->text_plain = __('Please follow this link to unban your IP: ') . SYMPHONY_URL . ABF::UNBAND_LINK . $failure[0]->Hash . '/' . PHP_EOL . __('If you do not remember your password, follow the "forgot password" link on the login page.') . PHP_EOL . __('The Symphony Team');
             // set error flag
             $this->_email_sent = $email->validate() && $email->send();
         } catch (Exception $e) {
             //var_dump($e);
             // do nothing
             $this->_email_sent = false;
         }
     }
 }
 /**
  * This function handles the Send Mail filter which will send an email
  * to each specified recipient informing them that an Entry has been
  * created.
  *
  * @param XMLElement $result
  *  The XMLElement of the XML that is going to be returned as part
  *  of this event to the page.
  * @param array $send_mail
  *  Associative array of `send-mail` parameters.
  * @param array $fields
  *  Array of post data to extract the values from
  * @param Section $section
  *  This Section for this event
  * @param Section $section
  *  This current Entry that has just been updated or created
  * @return XMLElement
  *  The modified `$result` with the results of the filter.
  */
 public function processSendMailFilter(XMLElement $result, array $send_email, array &$fields, Section $section, Entry $entry)
 {
     $fields['recipient'] = self::replaceFieldToken($send_email['recipient'], $fields);
     $fields['recipient'] = preg_split('/\\,/i', $fields['recipient'], -1, PREG_SPLIT_NO_EMPTY);
     $fields['recipient'] = array_map('trim', $fields['recipient']);
     $fields['subject'] = self::replaceFieldToken($send_email['subject'], $fields, __('[Symphony] A new entry was created on %s', array(Symphony::Configuration()->get('sitename', 'general'))));
     $fields['body'] = self::replaceFieldToken($send_email['body'], $fields, null, false, false);
     $fields['sender-email'] = self::replaceFieldToken($send_email['sender-email'], $fields);
     $fields['sender-name'] = self::replaceFieldToken($send_email['sender-name'], $fields);
     $fields['reply-to-name'] = self::replaceFieldToken($send_email['reply-to-name'], $fields);
     $fields['reply-to-email'] = self::replaceFieldToken($send_email['reply-to-email'], $fields);
     $edit_link = SYMPHONY_URL . '/publish/' . $section->get('handle') . '/edit/' . $entry->get('id') . '/';
     $language = Symphony::Configuration()->get('lang', 'symphony');
     $template_path = Event::getNotificationTemplate($language);
     $body = sprintf(file_get_contents($template_path), $section->get('name'), $edit_link);
     if (is_array($fields['body'])) {
         foreach ($fields['body'] as $field_handle => $value) {
             $body .= "// {$field_handle}" . PHP_EOL . $value . PHP_EOL . PHP_EOL;
         }
     } else {
         $body .= $fields['body'];
     }
     // Loop over all the recipients and attempt to send them an email
     // Errors will be appended to the Event XML
     $errors = array();
     foreach ($fields['recipient'] as $recipient) {
         $author = AuthorManager::fetchByUsername($recipient);
         if (empty($author)) {
             $errors['recipient'][$recipient] = __('Recipient not found');
             continue;
         }
         $email = Email::create();
         // Huib: Exceptions are also thrown in the settings functions, not only in the send function.
         // Those Exceptions should be caught too.
         try {
             $email->recipients = array($author->get('first_name') => $author->get('email'));
             if ($fields['sender-name'] != null) {
                 $email->sender_name = $fields['sender-name'];
             }
             if ($fields['sender-email'] != null) {
                 $email->sender_email_address = $fields['sender-email'];
             }
             if ($fields['reply-to-name'] != null) {
                 $email->reply_to_name = $fields['reply-to-name'];
             }
             if ($fields['reply-to-email'] != null) {
                 $email->reply_to_email_address = $fields['reply-to-email'];
             }
             $email->text_plain = str_replace('<!-- RECIPIENT NAME -->', $author->get('first_name'), $body);
             $email->subject = $fields['subject'];
             $email->send();
         } catch (EmailValidationException $e) {
             $errors['address'][$author->get('email')] = $e->getMessage();
         } catch (EmailGatewayException $e) {
             $errors['gateway'][$author->get('email')] = $e->getMessage();
         } catch (EmailException $e) {
             $errors['email'][$author->get('email')] = $e->getMessage();
         }
     }
     // If there were errors, output them to the event
     if (!empty($errors)) {
         $xml = self::buildFilterElement('send-email', 'failed');
         foreach ($errors as $type => $messages) {
             $xType = new XMLElement('error');
             $xType->setAttribute('error-type', $type);
             foreach ($messages as $recipient => $message) {
                 $xType->appendChild(new XMLElement('message', $message, array('recipient' => $recipient)));
             }
             $xml->appendChild($xType);
         }
         $result->appendChild($xml);
     } else {
         $result->appendChild(self::buildFilterElement('send-email', 'passed'));
     }
     return $result;
 }
 /**
  * Sends the email, either with the native {@link Email} class or with Postmark
  *
  * @param array The form data
  * @param Form The form object
  */
 public function sendEmail($data, $form)
 {
     $proxy = $form->proxy;
     $emailTo = $proxy->getToAddress();
     $emailSubject = $proxy->getMessageSubject();
     $replyTo = $proxy->getReplyTo();
     $emailTemplate = $proxy->getEmailTemplate();
     $fields = ArrayList::create(array());
     $uploadedFiles = array();
     foreach ($form->Fields()->dataFields() as $field) {
         if (!in_array($field->getName(), $proxy->getOmittedFields())) {
             if ($field instanceof CheckboxField) {
                 $value = $field->value ? _t('ContactForm.YES', 'Yes') : _t('ContactForm.NO', 'No');
             } elseif (class_exists("UploadifyField") && $field instanceof UploadifyField) {
                 $uploadedFiles[] = $field->Value();
             } else {
                 $value = nl2br($field->Value());
             }
             if (is_array($value)) {
                 $answers = ArrayList::create(array());
                 foreach ($value as $v) {
                     $answers->push(ArrayData::create(array('Value' => $v)));
                 }
                 $answers->Checkboxes = true;
                 $fields->push(ArrayData::create(array('Label' => $field->Title(), 'Values' => $answers)));
             } else {
                 $title = $field->Title() ? $field->Title() : $field->getName();
                 $fields->push(ArrayData::create(array('Label' => $title, 'Value' => $value)));
             }
         }
     }
     $messageData = array('IntroText' => $proxy->getIntroText(), 'Fields' => $fields, 'Domain' => Director::protocolAndHost());
     Requirements::clear();
     $html = $this->owner->customise($messageData)->renderWith($emailTemplate);
     Requirements::restore();
     if ($proxy->isPostmark()) {
         require_once Director::baseFolder() . "/contact_form/code/thirdparty/postmark/Postmark.php";
         $email = Mail_Postmark::compose()->subject($emailSubject)->messageHtml($html);
         try {
             $email->addTo($emailTo);
         } catch (Exception $e) {
             $form->sessionMessage(_t('ContactForm.BADTOADDRESS', 'It appears there is no receipient for this form. Please contact an administrator.'), 'bad');
             return $this->owner->redirectBack();
         }
         if ($replyTo) {
             try {
                 $email->replyTo($replyTo);
             } catch (Exception $e) {
             }
         }
         foreach ($uploadedFiles as $file_id) {
             if ($file = File::get()->byID($file_id)) {
                 $email->addAttachment($file->getFullPath());
             }
         }
     } else {
         $email = Email::create(null, $emailTo, $emailSubject, $html);
         if ($replyTo) {
             $email->replyTo($replyTo);
         }
         foreach ($uploadedFiles as $file_id) {
             if ($file = File::get()->byID($file_id)) {
                 $email->attachFile($file->getFullPath(), basename($file->Filename));
             }
         }
     }
     $email->send();
     foreach ($uploadedFiles as $file_id) {
         if ($file = File::get()->byID($file_id)->first()) {
             $file->delete();
         }
     }
 }
 public function sendBatch($pauth)
 {
     if ($this->getPAuth() != $pauth) {
         $this->setStatus('error');
         throw new EmailNewsletterException('Incorrect Process Auth used. This usually means there is more than one process running. Aborting.');
     }
     $this->_completed = explode(', ', $this->getCompletedRecipientGroups());
     $recipients = $this->_getRecipients($this->limit);
     if (count($recipients) > 0) {
         try {
             $template = $this->getTemplate();
             $sender = $this->getSender();
             $about = $sender->about();
             $additional_headers = $sender->additional_headers;
             if (is_array($about['smtp'])) {
                 $email = Email::create('smtp');
                 $email->setSenderName($about['smtp']['from_name']);
                 $email->setSenderEmailAddress($about['smtp']['from_address']);
                 $email->setHost($about['smtp']['host']);
                 $email->setPort($about['smtp']['port']);
                 $email->setSecure($about['smtp']['secure']);
                 if ($about['smtp']['auth'] == 1) {
                     $email->setAuth(true);
                     $email->setUser($about['smtp']['username']);
                     $email->setPass($about['smtp']['password']);
                 }
             } elseif (is_array($about['amazon_ses'])) {
                 $email = Email::create('amazon_ses');
                 $email->setSenderName($about['amazon_ses']['from_name']);
                 $email->setSenderEmailAddress($about['amazon_ses']['from_address']);
                 $email->setAwsKey($about['amazon_ses']['aws_key']);
                 $email->setAwsSecretKey($about['amazon_ses']['aws_secret_key']);
                 $email->setFallback($about['amazon_ses']['fallback']);
                 $email->setReturnPath($about['amazon_ses']['return_path']);
             } elseif (is_array($about['sendmail'])) {
                 $email = Email::create('sendmail');
                 $email->setSenderName($about['sendmail']['from_name']);
                 $email->setSenderEmailAddress($about['sendmail']['from_address']);
             } else {
                 throw new EmailNewsletterException('Currently only sendmail and SMTP are supported. This will be fixed when the API supports it.');
             }
         } catch (Exception $e) {
             file_put_contents(DOCROOT . '/manifest/newsletter-log.txt', '[' . DateTimeObj::get('Y/m/d H:i:s') . '] newsletter-id: ' . $this->getId() . ' - ' . $e->getMessage() . "\r\n", FILE_APPEND);
             return false;
         }
         $email->openConnection();
         foreach ($recipients as $recipient) {
             try {
                 /**
                  * @delegate PreEmailGenerate
                  */
                 Symphony::ExtensionManager()->notifyMembers('PreEmailGenerate', '/extension/email_newsletter_manager/', array('newsletter' => &$this, 'email' => &$email, 'template' => &$template, 'recipient' => &$recipient));
                 $email->setRecipients(array($recipient['name'] => $recipient['email']));
                 $template->recipients = '"' . $recipient['name'] . '" <' . $recipient['email'] . '>';
                 $template->addParams(array('etm-recipient' => $recipient['email']));
                 $email->setReplyToName($about['reply-to-name']);
                 $template->reply_to_name = $about['reply-to-name'];
                 $template->addParams(array('etm-reply-to-name' => $about['reply-to-name']));
                 $email->setReplyToEmailAddress($about['reply-to-email']);
                 $template->reply_to_email_address = $about['reply-to-email'];
                 $template->addParams(array('etm-reply-to-email-address' => $about['reply-to-email']));
                 if (!empty($additional_headers)) {
                     foreach ($additional_headers as $name => $body) {
                         $email->appendHeaderField($name, $body);
                     }
                 }
                 $template->addParams(array('enm-newsletter-id' => $this->getId()));
                 // add root and workspace parameters
                 $pseudo_root = $this->getPseudoRoot();
                 $template->addParams(array('root' => !empty($pseudo_root) ? $pseudo_root : NULL, 'workspace' => !empty($pseudo_root) ? $pseudo_root . '/workspace' : NULL));
                 $xml = $template->processDatasources();
                 $template->setXML($xml->generate());
                 $content = $template->render();
                 if (empty($content)) {
                     throw new EmailNewsletterException("ETM template could not be rendered");
                 }
                 if (!empty($content['subject'])) {
                     $email->subject = $content['subject'];
                 } else {
                     throw new EmailNewsletterException("Can not send emails without a subject");
                 }
                 if (isset($content['plain'])) {
                     $email->text_plain = $content['plain'];
                 }
                 if (isset($content['html'])) {
                     $email->text_html = $content['html'];
                 }
                 /**
                  * @delegate PreEmailSend
                  */
                 Symphony::ExtensionManager()->notifyMembers('PreEmailSend', '/extension/email_newsletter_manager/', array('newsletter' => &$this, 'email' => &$email, 'template' => &$template, 'recipient' => $recipient));
                 $email->send();
                 /**
                  * @delegate PostEmailSend
                  */
                 Symphony::ExtensionManager()->notifyMembers('PostEmailSend', '/extension/email_newsletter_manager/', array('newsletter' => &$this, 'email' => &$email, 'template' => &$template, 'recipient' => $recipient));
                 $this->_markRecipient($recipient['email'], 'sent');
             } catch (Exception $e) {
                 file_put_contents(DOCROOT . '/manifest/newsletter-log.txt', '[' . DateTimeObj::get('Y/m/d H:i:s') . '] newsletter-id: ' . $this->getId() . ' - ' . $e->getMessage() . "\r\n", FILE_APPEND);
                 $this->_markRecipient($recipient['email'], 'failed');
                 continue;
             }
         }
         $email->closeConnection();
     }
     //To prevent timing problems, the completed recipient groups should only be marked as complete when the emails are actually sent.
     Symphony::Database()->update(array('completed_recipients' => implode(', ', $this->_completed)), 'tbl_email_newsletters', 'id = ' . $this->getId());
     if (count($recipients) == 0) {
         Symphony::Database()->query('DROP TABLE IF EXISTS `tbl_tmp_email_newsletters_sent_' . $this->getId() . '`');
         $this->setStatus('completed');
         Symphony::Database()->update(array('completed_on' => date('Y-m-d H:i:s', time())), 'tbl_email_newsletters', 'id = ' . $this->getId());
         return 'completed';
     }
     return 'sent';
 }
Exemple #20
0
 public function action()
 {
     if (isset($_POST['action'])) {
         $actionParts = array_keys($_POST['action']);
         $action = end($actionParts);
         // Login Attempted
         if ($action == 'login') {
             if (empty($_POST['username']) || empty($_POST['password']) || !Administration::instance()->login($_POST['username'], $_POST['password'])) {
                 /**
                  * A failed login attempt into the Symphony backend
                  *
                  * @delegate AuthorLoginFailure
                  * @since Symphony 2.2
                  * @param string $context
                  * '/login/'
                  * @param string $username
                  *  The username of the Author who attempted to login.
                  */
                 Symphony::ExtensionManager()->notifyMembers('AuthorLoginFailure', '/login/', array('username' => Symphony::Database()->cleanValue($_POST['username'])));
                 $this->failedLoginAttempt = true;
             } else {
                 /**
                  * A successful login attempt into the Symphony backend
                  *
                  * @delegate AuthorLoginSuccess
                  * @since Symphony 2.2
                  * @param string $context
                  * '/login/'
                  * @param string $username
                  *  The username of the Author who logged in.
                  */
                 Symphony::ExtensionManager()->notifyMembers('AuthorLoginSuccess', '/login/', array('username' => Symphony::Database()->cleanValue($_POST['username'])));
                 isset($_POST['redirect']) ? redirect($_POST['redirect']) : redirect(SYMPHONY_URL . '/');
             }
             // Reset of password requested
         } elseif ($action == 'reset') {
             $author = Symphony::Database()->fetchRow(0, sprintf("\n                        SELECT `id`, `email`, `first_name`\n                        FROM `tbl_authors`\n                        WHERE `email` = '%1\$s' OR `username` = '%1\$s'\n                    ", Symphony::Database()->cleanValue($_POST['email'])));
             if (!empty($author)) {
                 Symphony::Database()->delete('tbl_forgotpass', sprintf("\n                        `expiry` < %d", DateTimeObj::getGMT('c')));
                 if (!($token = Symphony::Database()->fetchVar('token', 0, "SELECT `token` FROM `tbl_forgotpass` WHERE `expiry` > '" . DateTimeObj::getGMT('c') . "' AND `author_id` = " . $author['id']))) {
                     // More secure password token generation
                     if (function_exists('openssl_random_pseudo_bytes')) {
                         $seed = openssl_random_pseudo_bytes(16);
                     } else {
                         $seed = mt_rand();
                     }
                     $token = substr(SHA1::hash($seed), 0, 16);
                     Symphony::Database()->insert(array('author_id' => $author['id'], 'token' => $token, 'expiry' => DateTimeObj::getGMT('c', time() + 120 * 60)), 'tbl_forgotpass');
                 }
                 try {
                     $email = Email::create();
                     $email->recipients = $author['email'];
                     $email->subject = __('New Symphony Account Password');
                     $email->text_plain = __('Hi %s,', array($author['first_name'])) . PHP_EOL . __('A new password has been requested for your account. Login using the following link, and change your password via the Authors area:') . PHP_EOL . PHP_EOL . '    ' . SYMPHONY_URL . "/login/{$token}/" . PHP_EOL . PHP_EOL . __('It will expire in 2 hours. If you did not ask for a new password, please disregard this email.') . PHP_EOL . PHP_EOL . __('Best Regards,') . PHP_EOL . __('The Symphony Team');
                     $email->send();
                     $this->_email_sent = true;
                     $this->_email_sent_to = $author['email'];
                     // Set this so we can display a customised message
                 } catch (Exception $e) {
                     $this->_email_error = General::unwrapCDATA($e->getMessage());
                     Symphony::Log()->pushExceptionToLog($e, true);
                 }
                 /**
                  * When a password reset has occurred and after the Password
                  * Reset email has been sent.
                  *
                  * @delegate AuthorPostPasswordResetSuccess
                  * @since Symphony 2.2
                  * @param string $context
                  * '/login/'
                  * @param integer $author_id
                  *  The ID of the Author who requested the password reset
                  */
                 Symphony::ExtensionManager()->notifyMembers('AuthorPostPasswordResetSuccess', '/login/', array('author_id' => $author['id']));
             } else {
                 /**
                  * When a password reset has been attempted, but Symphony doesn't
                  * recognise the credentials the user has given.
                  *
                  * @delegate AuthorPostPasswordResetFailure
                  * @since Symphony 2.2
                  * @param string $context
                  * '/login/'
                  * @param string $email
                  *  The sanitised Email of the Author who tried to request the password reset
                  */
                 Symphony::ExtensionManager()->notifyMembers('AuthorPostPasswordResetFailure', '/login/', array('email' => Symphony::Database()->cleanValue($_POST['email'])));
                 $this->_email_sent = false;
             }
         }
     }
 }
 /**
  * Controller action that handles the "success" page
  *
  * @param   $r SS_HTTPRequest
  * @return SSViewer
  */
 public function success(SS_HTTPRequest $r)
 {
     $speakers = $this->presentation->Speakers()->exclude(array('MemberID' => $this->presentation->CreatorID));
     $this->presentation->Status = 'Received';
     $this->presentation->write();
     foreach ($speakers as $speaker) {
         $e = Email::create()->setTo($speaker->getEmail())->setUserTemplate('presentation-speaker-notification')->populateTemplate(array('RecipientMember' => $speaker->Member(), 'Presentation' => $this->presentation, 'Speaker' => $speaker, 'Creator' => $this->presentation->Creator(), 'EditLink' => Director::makeRelative($speaker->EditLink($this->presentation->ID)), 'ReviewLink' => Director::makeRelative($speaker->ReviewLink($this->presentation->ID)), 'PasswordLink' => Director::absoluteBaseURL() . '/lostpassword', 'Link' => Director::absoluteBaseURL() . Director::makeRelative($this->presentation->EditLink())))->send();
     }
     // Email the creator
     Email::create()->setTo($this->presentation->Creator()->Email)->setUserTemplate('presentation-creator-notification')->populateTemplate(array('Creator' => $this->presentation->Creator(), 'Summit' => $this->presentation->Summit(), 'Link' => Director::absoluteBaseURL() . Director::makeRelative($this->presentation->EditLink()), 'PasswordLink' => Director::absoluteBaseURL() . '/lostpassword'))->send();
     if ($this->presentation->Progress < Presentation::PHASE_COMPLETE) {
         $this->presentation->Progress = Presentation::PHASE_COMPLETE;
         $this->presentation->write();
     }
     return $this->renderWith(array('PresentationPage_success', 'PresentationPage'), $this->parent);
 }
 public function run()
 {
     Email::create([]);
 }
 public function sendEmail($entry_id, $template_id)
 {
     $template = $this->getTemplate($template_id);
     $conditions = $this->getConditions($template_id);
     $data = $this->getData($template, $entry_id);
     $xpath = new DOMXPath($data);
     $email = null;
     // Find condition:
     foreach ($conditions as $condition) {
         if (empty($condition['expression'])) {
             $email = $condition;
             break;
         }
         $results = $xpath->query($condition['expression']);
         if ($results->length > 0) {
             $email = $condition;
             break;
         }
     }
     if (is_null($email)) {
         return;
     }
     // Replace {xpath} queries:
     foreach ($email as $key => $value) {
         $content = $email[$key];
         $replacements = array();
         // Find queries:
         preg_match_all('/\\{[^\\}]+\\}/', $content, $matches);
         // Find replacements:
         foreach ($matches[0] as $match) {
             $results = @$xpath->query(trim($match, '{}'));
             if ($results->length) {
                 $items = array();
                 foreach ($results as $item) {
                     if (!isset($item->nodeValue)) {
                         continue;
                     }
                     $items[] = $item->nodeValue;
                 }
                 $replacements[$match] = implode(', ', $items);
             } else {
                 $replacements[$match] = '';
             }
         }
         $content = str_replace(array_keys($replacements), array_values($replacements), $content);
         $email[$key] = $content;
     }
     // Find generator:
     $page = $this->getPage($email['page']);
     $generator = URL;
     if ($page->path) {
         $generator .= '/' . $page->path;
     }
     $generator .= '/' . $page->handle;
     $generator = rtrim($generator, '/');
     $params = trim($email['params'], '/');
     $generator = "{$generator}/{$params}/";
     // Fetch generator
     require_once TOOLKIT . '/class.gateway.php';
     $ch = new Gateway();
     $ch->init($generator);
     $ch->setopt('HTTPHEADER', array('X-REQUESTED-WITH: EmailTemplateFilter'));
     $message = $ch->exec();
     // Add values:
     $email['message'] = (string) $message;
     $email['condition_id'] = $email['id'];
     $email['entry_id'] = $entry_id;
     $email['recipients'] = array_unique(preg_split('/\\s*[,]\\s*/', $email['recipients']));
     $email['reply_to'] = isset($email['reply_to']) ? $email['reply_to'] : $email['sender'];
     $email['reply_to_email'] = isset($email['reply_to_email']) ? $email['reply_to_email'] : $email['senders'];
     // Remove junk:
     unset($email['id']);
     unset($email['expression']);
     unset($email['type']);
     unset($email['sortorder']);
     unset($email['page']);
     unset($email['params']);
     $send = Email::create();
     $success = false;
     try {
         $send->recipients = $email['recipients'];
         $send->sender_name = $email['sender'];
         $send->sender_email_address = $email['senders'];
         $send->reply_to_name = $email['reply_to'];
         $send->reply_to_email_address = $email['reply_to_email'];
         $send->subject = $email['subject'];
         $send->text_html = $email['message'];
         $send->attachments = $this->findAttachments($email);
         $send->send();
         $success = true;
     } catch (EmailGatewayException $e) {
         throw new SymphonyErrorPage('Error sending email. ' . $e->getMessage());
     } catch (EmailException $e) {
         throw new SymphonyErrorPage('Error sending email. ' . $e->getMessage());
     }
     // Log the email:
     $email['success'] = $success ? 'yes' : 'no';
     $email['date'] = DateTimeObj::get('c');
     $email['recipients'] = implode(', ', $email['recipients']);
     Symphony::Database()->insert($email, 'tbl_etf_logs');
     return $return;
 }
 /**
  * I would actually advice to change a few things here, personally.
  */
 public function onAfterWrite()
 {
     $SiteConfig = SiteConfig::current_site_config();
     /** No, really, I mean it. Change this. When spambots find your site, 30 e-mails an hour is NORMAL! */
     $mail = Email::create();
     $mail->setTo($SiteConfig->NewsEmail);
     $mail->setSubject(_t('Comment.COMMENTMAILSUBJECT2', 'New post titled: {title} ', array('title' => $this->Title)));
     $mail->setFrom($this->Email);
     $mail->setTemplate('CommentPost');
     $mail->populateTemplate($this);
     $mail->send();
 }
Exemple #25
0
 require_once(INCLUDE_DIR.'class.email.php');
 $do=strtolower($_POST['do']);
 switch($do){
     case 'update':
         $email = new Email($_POST['email_id']);
         if($email && $email->getId()) {
             if($email->update($_POST,$errors))
                 $msg='Email updated successfully';
             elseif(!$errors['err'])
                 $errors['err']='Error updating email';
         }else{
             $errors['err']='Internal error';
         }
         break;
     case 'create':
         if(Email::create($_POST,$errors))
             $msg='Email added successfully';
         elseif(!$errors['err'])
              $errors['err']='Unable to add email. Internal error';
         break;
     case 'mass_process':
         if(!$_POST['ids'] || !is_array($_POST['ids'])) {
             $errors['err']='You must select at least one email to process';
         }else{
             $count=count($_POST['ids']);
             $ids=implode(',',$_POST['ids']);
             $sql='SELECT count(dept_id) FROM '.DEPT_TABLE.' WHERE email_id IN ('.$ids.') OR autoresp_email_id IN ('.$ids.')';
             list($depts)=db_fetch_row(db_query($sql));
             if($depts>0){
                 $errors['err']='One or more of the selected emails is being used by a Dept. Remove association first.';    
             }elseif($_POST['delete']){
 /**
  * Allows you to send emails. It initializes the core email class.
  *
  * @deprecated Since Symphony 2.2
  * @param string $to_email
  *  email of the recipient
  * @param string $from_email
  *  the from email address. This is usually your email
  * @param string $from_name
  *  the name of the sender
  * @param string $subject
  *  subject of the email
  * @param string $message
  *  contents of the email
  * @param array $additional_headers
  *  an array containing additional email headers. This will NOT work
  *  for Content-Type header fields which will be added/overwritten by
  *  the email gateways.)
  * @return boolean
  *  true on success
  */
 public static function sendEmail($to_email, $from_email, $from_name, $subject, $message, array $additional_headers = array())
 {
     try {
         $email = Email::create();
         if (!empty($additional_headers)) {
             foreach ($additional_headers as $name => $body) {
                 $email->appendHeaderField($name, $body);
             }
         }
         $email->sender_name = $from_name;
         $email->sender_email_address = $from_email;
         $email->recipients = $email->setRecipients($to_email);
         $email->text_plain = $message;
         $email->subject = $subject;
         return $email->send();
     } catch (EmailGatewayException $e) {
         throw new SymphonyErrorPage('Error sending email. ' . $e->getMessage());
     } catch (EmailException $e) {
         throw new SymphonyErrorPage('Error sending email. ' . $e->getMessage());
     }
 }
 /**
  * Sends a welcome email to the user     
  */
 public function sendWelcomeEmail()
 {
     Email::create()->setTo($this->owner->Email)->setUserTemplate('member-welcome')->populateTemplate(array('Member' => $this->owner))->send();
 }
 protected function sendApprovalCancellationEmail(\DNDeployment $deployment)
 {
     if (!$this->canSendEmail($deployment)) {
         return false;
     }
     $deployer = $deployment->Deployer();
     $approver = $deployment->Approver();
     $to = sprintf('%s <%s>, %s <%s>', $deployer->Name, $deployer->Email, $approver->Name, $approver->Email);
     $email = Email::create();
     $email->setTo($to);
     $email->setSubject('Deployment approval has been cancelled');
     $email->setTemplate('DeploymentApprovalCancellationEmail');
     $email->populateTemplate($deployment);
     $email->send();
     $deployment->log()->write(sprintf('Deployment approval cancellation email sent to %s', $to));
 }
 public function __doit($fields, &$result, $position = null, $entry_id = null)
 {
     $post_values = new XMLElement('post-values');
     $filter_results = array();
     if (!is_array($this->eParamFILTERS)) {
         $this->eParamFILTERS = array();
     }
     // Create the post data cookie element
     if (is_array($fields) && !empty($fields)) {
         General::array_to_xml($post_values, $fields, true);
     }
     /**
      * Prior to saving entry from the front-end. This delegate will
      * force the Event to terminate if it populates the `$filter_results`
      * array. All parameters are passed by reference.
      *
      * @delegate EventPreSaveFilter
      * @param string $context
      * '/frontend/'
      * @param array $fields
      * @param Event $this
      * @param array $messages
      *  An associative array of array's which contain 4 values,
      *  the name of the filter (string), the status (boolean),
      *  the message (string) an optionally an associative array
      *  of additional attributes to add to the filter element.
      * @param XMLElement $post_values
      * @param integer $entry_id
      *  If editing an entry, this parameter will be an integer,
      *  otherwise null.
      */
     Symphony::ExtensionManager()->notifyMembers('EventPreSaveFilter', '/frontend/', array('fields' => &$fields, 'event' => &$this, 'messages' => &$filter_results, 'post_values' => &$post_values, 'entry_id' => &$entry_id));
     if (is_array($filter_results) && !empty($filter_results)) {
         $can_proceed = true;
         foreach ($filter_results as $fr) {
             list($name, $status, $message, $attributes) = $fr;
             $result->appendChild($this->buildFilterElement($name, $status ? 'passed' : 'failed', $message, $attributes));
             if ($status === false) {
                 $can_proceed = false;
             }
         }
         if ($can_proceed !== true) {
             $result->appendChild($post_values);
             $result->setAttribute('result', 'error');
             $result->appendChild(new XMLElement('message', __('Entry encountered errors when saving.')));
             return false;
         }
     }
     include_once TOOLKIT . '/class.sectionmanager.php';
     include_once TOOLKIT . '/class.entrymanager.php';
     if (!($section = SectionManager::fetch($this->getSource()))) {
         $result->setAttribute('result', 'error');
         $result->appendChild(new XMLElement('message', __('The Section, %s, could not be found.', array($this->getSource()))));
         return false;
     }
     if (isset($entry_id)) {
         $entry =& EntryManager::fetch($entry_id);
         $entry = $entry[0];
         if (!is_object($entry)) {
             $result->setAttribute('result', 'error');
             $result->appendChild(new XMLElement('message', __('The Entry, %s, could not be found.', array($entry_id))));
             return false;
         }
     } else {
         $entry =& EntryManager::create();
         $entry->set('section_id', $this->getSource());
     }
     if (__ENTRY_FIELD_ERROR__ == $entry->checkPostData($fields, $errors, $entry->get('id') ? true : false)) {
         $result->setAttribute('result', 'error');
         $result->appendChild(new XMLElement('message', __('Entry encountered errors when saving.')));
         foreach ($errors as $field_id => $message) {
             $field = FieldManager::fetch($field_id);
             if (is_array($fields[$field->get('element_name')])) {
                 $type = array_reduce($fields[$field->get('element_name')], array('SectionEvent', '__reduceType'));
             } else {
                 $type = $fields[$field->get('element_name')] == '' ? 'missing' : 'invalid';
             }
             $result->appendChild(new XMLElement($field->get('element_name'), null, array('label' => General::sanitize($field->get('label')), 'type' => $type, 'message' => General::sanitize($message))));
         }
         if (isset($post_values) && is_object($post_values)) {
             $result->appendChild($post_values);
         }
         return false;
     } elseif (__ENTRY_OK__ != $entry->setDataFromPost($fields, $errors, false, $entry->get('id') ? true : false)) {
         $result->setAttribute('result', 'error');
         $result->appendChild(new XMLElement('message', __('Entry encountered errors when saving.')));
         foreach ($errors as $field_id => $message) {
             $field = FieldManager::fetch($field_id);
             $result->appendChild(new XMLElement($field->get('element_name'), null, array('label' => General::sanitize($field->get('label')), 'type' => 'invalid', 'message' => General::sanitize($message))));
         }
         if (isset($post_values) && is_object($post_values)) {
             $result->appendChild($post_values);
         }
         return false;
     } else {
         if (!$entry->commit()) {
             $result->setAttribute('result', 'error');
             $result->appendChild(new XMLElement('message', __('Unknown errors where encountered when saving.')));
             if (isset($post_values) && is_object($post_values)) {
                 $result->appendChild($post_values);
             }
             return false;
         }
         $result->setAttribute('id', $entry->get('id'));
     }
     // PASSIVE FILTERS ONLY AT THIS STAGE. ENTRY HAS ALREADY BEEN CREATED.
     if (in_array('send-email', $this->eParamFILTERS) && !in_array('expect-multiple', $this->eParamFILTERS)) {
         if (!function_exists('__sendEmailFindFormValue')) {
             function __sendEmailFindFormValue($needle, $haystack, $discard_field_name = true, $default = null, $collapse = true)
             {
                 if (preg_match('/^(fields\\[[^\\]]+\\],?)+$/i', $needle)) {
                     $parts = preg_split('/\\,/i', $needle, -1, PREG_SPLIT_NO_EMPTY);
                     $parts = array_map('trim', $parts);
                     $stack = array();
                     foreach ($parts as $p) {
                         $field = str_replace(array('fields[', ']'), '', $p);
                         $discard_field_name ? $stack[] = $haystack[$field] : ($stack[$field] = $haystack[$field]);
                     }
                     if (is_array($stack) && !empty($stack)) {
                         return $collapse ? implode(' ', $stack) : $stack;
                     } else {
                         $needle = null;
                     }
                 }
                 $needle = trim($needle);
                 if (empty($needle)) {
                     return $default;
                 }
                 return $needle;
             }
         }
         $fields = $_POST['send-email'];
         $db = Symphony::Database();
         $fields['recipient'] = __sendEmailFindFormValue($fields['recipient'], $_POST['fields'], true);
         $fields['recipient'] = preg_split('/\\,/i', $fields['recipient'], -1, PREG_SPLIT_NO_EMPTY);
         $fields['recipient'] = array_map('trim', $fields['recipient']);
         $fields['subject'] = __sendEmailFindFormValue($fields['subject'], $_POST['fields'], true, __('[Symphony] A new entry was created on %s', array(Symphony::Configuration()->get('sitename', 'general'))));
         $fields['body'] = __sendEmailFindFormValue($fields['body'], $_POST['fields'], false, null, false);
         $fields['sender-email'] = __sendEmailFindFormValue($fields['sender-email'], $_POST['fields'], true, null);
         $fields['sender-name'] = __sendEmailFindFormValue($fields['sender-name'], $_POST['fields'], true, null);
         $fields['reply-to-name'] = __sendEmailFindFormValue($fields['reply-to-name'], $_POST['fields'], true, null);
         $fields['reply-to-email'] = __sendEmailFindFormValue($fields['reply-to-email'], $_POST['fields'], true, null);
         $edit_link = SYMPHONY_URL . '/publish/' . $section->get('handle') . '/edit/' . $entry->get('id') . '/';
         $language = Symphony::Configuration()->get('lang', 'symphony');
         $template_path = Event::getNotificationTemplate($language);
         $body = sprintf(file_get_contents($template_path), $section->get('name'), $edit_link);
         if (is_array($fields['body'])) {
             foreach ($fields['body'] as $field_handle => $value) {
                 $body .= "// {$field_handle}" . PHP_EOL . $value . PHP_EOL . PHP_EOL;
             }
         } else {
             $body .= $fields['body'];
         }
         // Loop over all the recipients and attempt to send them an email
         // Errors will be appended to the Event XML
         $errors = array();
         foreach ($fields['recipient'] as $recipient) {
             $author = AuthorManager::fetchByUsername($recipient);
             if (empty($author)) {
                 $errors['recipient'][$recipient] = __('Recipient not found');
                 continue;
             }
             $email = Email::create();
             // Huib: Exceptions are also thrown in the settings functions, not only in the send function.
             // Those Exceptions should be caught too.
             try {
                 $email->recipients = array($author->get('first_name') => $author->get('email'));
                 if ($fields['sender-name'] != null) {
                     $email->sender_name = $fields['sender-name'];
                 }
                 if ($fields['sender-email'] != null) {
                     $email->sender_email_address = $fields['sender-email'];
                 }
                 if ($fields['reply-to-name'] != null) {
                     $email->reply_to_name = $fields['reply-to-name'];
                 }
                 if ($fields['reply-to-email'] != null) {
                     $email->reply_to_email_address = $fields['reply-to-email'];
                 }
                 $email->text_plain = str_replace('<!-- RECIPIENT NAME -->', $author->get('first_name'), $body);
                 $email->subject = $fields['subject'];
                 $email->send();
             } catch (EmailValidationException $e) {
                 $errors['address'][$author->get('email')] = $e->getMessage();
             } catch (EmailGatewayException $e) {
                 // The current error array does not permit custom tags.
                 // Therefore, it is impossible to set a "proper" error message.
                 // Will return the failed email address instead.
                 $errors['gateway'][$author->get('email')] = $e->getMessage();
             } catch (EmailException $e) {
                 // Because we don't want symphony to break because it can not send emails,
                 // all exceptions are logged silently.
                 // Any custom event can change this behaviour.
                 $errors['email'][$author->get('email')] = $e->getMessage();
             }
         }
         // If there were errors, output them to the event
         if (!empty($errors)) {
             $xml = $this->buildFilterElement('send-email', 'failed');
             foreach ($errors as $type => $messages) {
                 $xType = new XMLElement('error');
                 $xType->setAttribute('error-type', $type);
                 foreach ($messages as $recipient => $message) {
                     $xType->appendChild(new XMLElement('message', $message, array('recipient' => $recipient)));
                 }
                 $xml->appendChild($xType);
             }
             $result->appendChild($xml);
         } else {
             $result->appendChild($this->buildFilterElement('send-email', 'passed'));
         }
     }
     $filter_results = array();
     /**
      * After saving entry from the front-end. This delegate will not force
      * the Events to terminate if it populates the `$filter_results` array.
      * Provided with references to this object, the `$_POST` data and also
      * the error array
      *
      * @delegate EventPostSaveFilter
      * @param string $context
      * '/frontend/'
      * @param integer $entry_id
      * @param array $fields
      * @param Entry $entry
      * @param Event $this
      * @param array $messages
      *  An associative array of array's which contain 4 values,
      *  the name of the filter (string), the status (boolean),
      *  the message (string) an optionally an associative array
      *  of additional attributes to add to the filter element.
      */
     Symphony::ExtensionManager()->notifyMembers('EventPostSaveFilter', '/frontend/', array('entry_id' => $entry->get('id'), 'fields' => $fields, 'entry' => $entry, 'event' => &$this, 'messages' => &$filter_results));
     if (is_array($filter_results) && !empty($filter_results)) {
         foreach ($filter_results as $fr) {
             list($name, $status, $message, $attributes) = $fr;
             $result->appendChild($this->buildFilterElement($name, $status ? 'passed' : 'failed', $message, $attributes));
         }
     }
     $filter_errors = array();
     /**
      * This delegate that lets extensions know the final status of the
      * current Event. It is triggered when everything has processed correctly.
      * The `$messages` array contains the results of the previous filters that
      * have executed, and the `$errors` array contains any errors that have
      * occurred as a result of this delegate. These errors cannot stop the
      * processing of the Event, as that has already been done.
      *
      *
      * @delegate EventFinalSaveFilter
      * @param string $context
      * '/frontend/'
      * @param array $fields
      * @param Event $this
      * @param array $messages
      *  An associative array of array's which contain 4 values,
      *  the name of the filter (string), the status (boolean),
      *  the message (string) an optionally an associative array
      *  of additional attributes to add to the filter element.
      * @param array $errors
      *  An associative array of array's which contain 4 values,
      *  the name of the filter (string), the status (boolean),
      *  the message (string) an optionally an associative array
      *  of additional attributes to add to the filter element.
      * @param Entry $entry
      */
     Symphony::ExtensionManager()->notifyMembers('EventFinalSaveFilter', '/frontend/', array('fields' => $fields, 'event' => $this, 'messages' => $filter_results, 'errors' => &$filter_errors, 'entry' => $entry));
     if (is_array($filter_errors) && !empty($filter_errors)) {
         foreach ($filter_errors as $fr) {
             list($name, $status, $message, $attributes) = $fr;
             $result->appendChild($this->buildFilterElement($name, $status ? 'passed' : 'failed', $message, $attributes));
         }
     }
     $result->setAttributeArray(array('result' => 'success', 'type' => isset($entry_id) ? 'edited' : 'created'));
     $result->appendChild(new XMLElement('message', isset($entry_id) ? __('Entry edited successfully.') : __('Entry created successfully.')));
     if (isset($post_values) && is_object($post_values)) {
         $result->appendChild($post_values);
     }
     return true;
 }
Exemple #30
0
 public function sendAdminEmail($member)
 {
     $email = Email::create();
     $email->setTo('*****@*****.**');
     $email->setBcc('*****@*****.**');
     $email->setSubject("New member application");
     $content = $this->customise(new ArrayData(array('Member' => $member)))->renderWith('NewMemberEmail');
     $email->setBody($content);
     $email->send();
 }