Replace own emailer to SwiftMailer.

This commit is contained in:
Yuriy Pikhtarev 2017-05-21 15:00:01 +03:00
commit b2fdf0b2a9
No known key found for this signature in database
GPG key ID: 3A9B5A757B48ECC6
13 changed files with 406 additions and 552 deletions

View file

@ -49,7 +49,8 @@ TorrentPier - движок торрент-трекера, написанный
## Необходимые модули php
php5-tidy
intl
tidy
Начиная с версии 2.0.9 (ревизия 592 в старой нумерации) данный модуль не является обязательным, но его установка крайне рекомендуется для повышения качества обработки html-кода тем и сообщений пользователей.
## Рекомендуемый способ запуска cron.php

View file

@ -76,22 +76,21 @@ if (isset($_POST['submit'])) {
");
}
require CLASS_DIR . '/emailer.php';
foreach ($user_list as $i => $row) {
$emailer = new emailer($bb_cfg['smtp_delivery']);
/** @var TorrentPier\Legacy\Emailer() $emailer */
$emailer = new TorrentPier\Legacy\Emailer();
$emailer->from($bb_cfg['sitename'] . " <{$bb_cfg['board_email']}>");
$emailer->email_address($row['username'] . " <{$row['user_email']}>");
$emailer->use_template('admin_send_email');
$emailer->set_from([$bb_cfg['board_email'] => $bb_cfg['sitename']]);
$emailer->set_to([$row['user_email'] => $row['username']]);
$emailer->set_subject($subject);
$emailer->set_template('admin_send_email');
$emailer->assign_vars(array(
'SUBJECT' => html_entity_decode($subject),
'MESSAGE' => html_entity_decode($message),
));
$emailer->send();
$emailer->reset();
}
}
}

View file

@ -43,7 +43,9 @@
"require": {
"php": "^5.3 || ^7.0",
"gigablah/sphinxphp": "^2.0",
"google/recaptcha": "^1.0"
"google/recaptcha": "^1.0",
"roave/security-advisories": "dev-master",
"swiftmailer/swiftmailer": "^6.0"
},
"autoload": {
"psr-4": {

View file

@ -213,14 +213,14 @@ if (!$group_id) {
add_user_into_group($group_id, $userdata['user_id'], 1, TIMENOW);
if ($bb_cfg['group_send_email']) {
require CLASS_DIR . '/emailer.php';
$emailer = new emailer($bb_cfg['smtp_delivery']);
/** @var TorrentPier\Legacy\Emailer() $emailer */
$emailer = new TorrentPier\Legacy\Emailer();
$emailer->from($bb_cfg['sitename'] . " <{$bb_cfg['board_email']}>");
$emailer->email_address($moderator['username'] . " <{$moderator['user_email']}>");
$emailer->use_template('group_request', $moderator['user_lang']);
$emailer->set_from([$bb_cfg['board_email'] => $bb_cfg['sitename']]);
$emailer->set_to([$moderator['user_email'] => $moderator['username']]);
$emailer->set_subject($lang['EMAILER_SUBJECT']['GROUP_REQUEST']);
$emailer->set_template('group_request', $moderator['user_lang']);
$emailer->assign_vars(array(
'USER' => $userdata['username'],
'SITENAME' => $bb_cfg['sitename'],
@ -229,7 +229,6 @@ if (!$group_id) {
));
$emailer->send();
$emailer->reset();
}
set_die_append_msg(false, false, $group_id);
@ -256,14 +255,14 @@ if (!$group_id) {
add_user_into_group($group_id, $row['user_id']);
if ($bb_cfg['group_send_email']) {
require CLASS_DIR . '/emailer.php';
$emailer = new emailer($bb_cfg['smtp_delivery']);
/** @var TorrentPier\Legacy\Emailer() $emailer */
$emailer = new TorrentPier\Legacy\Emailer();
$emailer->from($bb_cfg['sitename'] . " <{$bb_cfg['board_email']}>");
$emailer->email_address($row['username'] . " <{$row['user_email']}>");
$emailer->use_template('group_added', $row['user_lang']);
$emailer->set_from([$bb_cfg['board_email'] => $bb_cfg['sitename']]);
$emailer->set_to([$row['user_email'] => $row['username']]);
$emailer->set_subject($lang['EMAILER_SUBJECT']['GROUP_ADDED']);
$emailer->set_template('group_added', $row['user_lang']);
$emailer->assign_vars(array(
'SITENAME' => $bb_cfg['sitename'],
'GROUP_NAME' => $group_info['group_name'],
@ -271,7 +270,6 @@ if (!$group_id) {
));
$emailer->send();
$emailer->reset();
}
} else {
if (((!empty($_POST['approve']) || !empty($_POST['deny'])) && !empty($_POST['pending_members'])) || (!empty($_POST['remove']) && !empty($_POST['members']))) {
@ -315,24 +313,23 @@ if (!$group_id) {
bb_die('Could not get user email information');
}
require CLASS_DIR . '/emailer.php';
$emailer = new emailer($bb_cfg['smtp_delivery']);
$emailer->from($bb_cfg['sitename'] . " <{$bb_cfg['board_email']}>");
foreach (DB()->fetch_rowset($sql_select) as $row) {
$emailer->use_template('group_approved', $row['user_lang']);
$emailer->email_address($row['username'] . " <{$row['user_email']}>");
/** @var TorrentPier\Legacy\Emailer() $emailer */
$emailer = new TorrentPier\Legacy\Emailer();
$emailer->set_from([$bb_cfg['board_email'] => $bb_cfg['sitename']]);
$emailer->set_to([$row['user_email'] => $row['username']]);
$emailer->set_subject($lang['EMAILER_SUBJECT']['GROUP_APPROVED']);
$emailer->set_template('group_approved', $row['user_lang']);
$emailer->assign_vars(array(
'SITENAME' => $bb_cfg['sitename'],
'GROUP_NAME' => $group_info['group_name'],
'U_GROUP' => make_url(GROUP_URL . $group_id),
));
$emailer->send();
}
$emailer->assign_vars(array(
'SITENAME' => $bb_cfg['sitename'],
'GROUP_NAME' => $group_info['group_name'],
'U_GROUP' => make_url(GROUP_URL . $group_id),
));
$emailer->send();
$emailer->reset();
}
}
}

View file

@ -98,7 +98,7 @@ $domain_name = (!empty($_SERVER['SERVER_NAME'])) ? $_SERVER['SERVER_NAME'] : $do
// Version info
$bb_cfg['tp_version'] = '2.1.6';
$bb_cfg['tp_release_date'] = '**-02-2017';
$bb_cfg['tp_release_date'] = '01-07-2017';
$bb_cfg['tp_release_state'] = 'STABLE';
// Database
@ -360,7 +360,7 @@ $page_cfg['show_sidebar2'] = array(
);
// Cookie
$bb_cfg['cookie_domain'] = in_array($domain_name, array(getenv('SERVER_ADDR'), 'localhost')) ? '' : ".$domain_name";
$bb_cfg['cookie_domain'] = in_array($domain_name, array(getenv('SERVER_ADDR'), 'localhost'), true) ? '' : ".$domain_name";
$bb_cfg['cookie_secure'] = (!empty($_SERVER['HTTPS']) ? 1 : 0);
$bb_cfg['cookie_prefix'] = 'bb_'; // 'bb_'
@ -381,14 +381,17 @@ $bb_cfg['new_user_reg_restricted'] = false; // Ограничить ре
$bb_cfg['reg_email_activation'] = true; // Требовать активацию учетной записи по email
// Email
$bb_cfg['emailer_disabled'] = false;
$bb_cfg['smtp_delivery'] = false; // send email via a named server instead of the local mail function
$bb_cfg['smtp_ssl'] = false; // use ssl connect
$bb_cfg['smtp_host'] = ''; // SMTP server host
$bb_cfg['smtp_port'] = 25; // SMTP server port
$bb_cfg['smtp_username'] = ''; // enter a username if your SMTP server requires it
$bb_cfg['smtp_password'] = ''; // enter a password if your SMTP server requires it
$bb_cfg['emailer'] = [
'enabled' => true,
'smtp' => [
'enabled' => true, // send email via external SMTP server
'host' => '', // SMTP server host
'port' => 25, // SMTP server port
'username' => '', // SMTP username (if server requires it)
'password' => '', // SMTP password (if server requires it)
],
'ssl_type' => '', // SMTP ssl type (ssl or tls)
];
$bb_cfg['board_email'] = "noreply@$domain_name"; // admin email address
$bb_cfg['board_email_form'] = false; // can users send email to each other via board
@ -532,7 +535,7 @@ $bb_cfg['user_not_active_days_keep'] = 180; // inactive users but only with
$bb_cfg['group_members_per_page'] = 50;
// Tidy
$bb_cfg['tidy_post'] = (!in_array('tidy', get_loaded_extensions())) ? false : true;
$bb_cfg['tidy_post'] = (!in_array('tidy', get_loaded_extensions(), true)) ? false : true;
// Ads
$bb_cfg['show_ads'] = false;
@ -554,7 +557,7 @@ $bb_cfg['ad_blocks'] = array(
// Misc
define('MEM_USAGE', function_exists('memory_get_usage'));
$bb_cfg['mem_on_start'] = (MEM_USAGE) ? memory_get_usage() : 0;
$bb_cfg['mem_on_start'] = MEM_USAGE ? memory_get_usage() : 0;
$bb_cfg['translate_dates'] = true; // in displaying time
$bb_cfg['use_word_censor'] = true;
@ -568,7 +571,7 @@ $bb_cfg['allow_change'] = array(
'dateformat' => true,
);
define('GZIP_OUTPUT_ALLOWED', (extension_loaded('zlib') && !ini_get('zlib.output_compression')));
define('GZIP_OUTPUT_ALLOWED', extension_loaded('zlib') && !ini_get('zlib.output_compression'));
$banned_user_agents = array(
// Download Master

View file

@ -1,234 +0,0 @@
<?php
/**
* MIT License
*
* Copyright (c) 2005-2017 TorrentPier
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
if (!defined('BB_ROOT')) {
die(basename(__FILE__));
}
class emailer
{
public $msg;
public $subject;
public $extra_headers;
public $addresses;
public $reply_to;
public $from;
public $use_smtp;
public $tpl_msg = array();
public $vars = array();
public function __construct($use_smtp/*$tpl_name, $sbj, $to_address*/)
{
global $bb_cfg;
$this->reset();
$this->from = $bb_cfg['board_email'];
$this->reply_to = $bb_cfg['board_email'];
$this->use_smtp = $use_smtp; /*!empty($bb_cfg['smtp_host']);
$this->use_template($tpl_name);
$this->set_subject($sbj);
$this->email_address($to_address);*/
}
public function set_default_vars()
{
global $bb_cfg;
$this->vars = array(
'BOARD_EMAIL' => $bb_cfg['board_email'],
'SITENAME' => $bb_cfg['board_email_sitename'],
'EMAIL_SIG' => !empty($bb_cfg['board_email_sig']) ? "-- \n{$bb_cfg['board_email_sig']}" : '',
);
}
// Resets all the data (address, template file, etc etc to default
public function reset()
{
$this->addresses = array();
$this->msg = $this->extra_headers = '';
$this->set_default_vars();
}
// Sets an email address to send to
public function email_address($address)
{
$this->addresses['to'] = trim($address);
}
public function cc($address)
{
$this->addresses['cc'][] = trim($address);
}
public function bcc($address)
{
$this->addresses['bcc'][] = trim($address);
}
public function replyto($address)
{
$this->reply_to = trim($address);
}
public function from($address)
{
$this->from = trim($address);
}
// set up subject for mail
public function set_subject($subject = '')
{
$this->subject = trim(preg_replace('#[\n\r]+#s', '', $subject));
}
// set up extra mail headers
public function extra_headers($headers)
{
$this->extra_headers .= trim($headers) . "\n";
}
public function use_template($template_file, $template_lang = '')
{
global $bb_cfg;
if (!$template_lang) {
$template_lang = $bb_cfg['default_lang'];
}
if (empty($this->tpl_msg[$template_lang . $template_file])) {
$tpl_file = LANG_ROOT_DIR . '/' . $template_lang . '/email/' . $template_file . '.html';
if (!file_exists($tpl_file)) {
$tpl_file = LANG_ROOT_DIR . '/' . $bb_cfg['default_lang'] . '/email/' . $template_file . '.html';
if (!file_exists($tpl_file)) {
bb_die('Could not find email template file :: ' . $template_file);
}
}
if (!($fd = @fopen($tpl_file, 'rb'))) {
bb_die('Failed opening template file :: ' . $tpl_file);
}
$this->tpl_msg[$template_lang . $template_file] = fread($fd, filesize($tpl_file));
fclose($fd);
}
$this->msg = $this->tpl_msg[$template_lang . $template_file];
return true;
}
// assign variables
public function assign_vars($vars)
{
$this->vars = array_merge($this->vars, $vars);
}
// Send the mail out to the recipients set previously in var $this->address
public function send($email_format = 'text')
{
global $bb_cfg, $userdata;
if ($bb_cfg['emailer_disabled']) {
return;
}
// Escape all quotes
$this->msg = str_replace("'", "\'", $this->msg);
$this->msg = preg_replace('#\{([a-z0-9\-_]*?)\}#is', "' . $\\1 . '", $this->msg);
// Set vars
reset($this->vars);
foreach ($this->vars as $key => $val) {
$this->msg = preg_replace(sprintf('/\$\{?%s\}?/', $key), $val, $this->msg);
}
// We now try and pull a subject from the email body ... if it exists,
// do this here because the subject may contain a variable
$drop_header = '';
$match = [];
if (preg_match('#^(Subject:(.*?))$#m', $this->msg, $match)) {
$this->subject = (trim($match[2]) != '') ? trim($match[2]) : (($this->subject != '') ? $this->subject : 'No Subject');
$drop_header .= '[\r\n]*?' . preg_quote($match[1], '#');
} else {
$this->subject = (($this->subject != '') ? $this->subject : 'No Subject');
}
$this->encoding = trim($bb_cfg['lang'][$userdata['user_lang']]['encoding']);
$this->subject = $this->encode($this->subject);
if ($drop_header != '') {
$this->msg = trim(preg_replace('#' . $drop_header . '#s', '', $this->msg));
}
$to = @$this->addresses['to'];
$cc = (@count($this->addresses['cc'])) ? implode(', ', $this->addresses['cc']) : '';
$bcc = (@count($this->addresses['bcc'])) ? implode(', ', $this->addresses['bcc']) : '';
// Build header
$type = ($email_format == 'html') ? 'html' : 'plain';
$this->extra_headers = (($this->reply_to != '') ? "Reply-to: $this->reply_to\n" : '') . (($this->from != '') ? "From: $this->from\n" : "From: " . $bb_cfg['board_email'] . "\n") . "Return-Path: " . $bb_cfg['board_email'] . "\nMessage-ID: <" . md5(uniqid(TIMENOW, true)) . "@" . $bb_cfg['server_name'] . ">\nMIME-Version: 1.0\nContent-type: text/$type; charset=" . $this->encoding . "\nContent-transfer-encoding: 8bit\nDate: " . date('r', TIMENOW) . "\nX-Priority: 0\nX-MSMail-Priority: Normal\nX-Mailer: Microsoft Office Outlook, Build 11.0.5510\nX-MimeOLE: Produced By Microsoft MimeOLE V6.00.2800.1441\nX-Sender: " . $bb_cfg['board_email'] . "\n" . $this->extra_headers . (($cc != '') ? "Cc: $cc\n" : '') . (($bcc != '') ? "Bcc: $bcc\n" : '');
// Send message
if ($this->use_smtp) {
if (!defined('SMTP_INCLUDED')) {
include INC_DIR . '/smtp.php';
}
$result = smtpmail($to, $this->subject, $this->msg, $this->extra_headers);
} else {
$to = ($to == '') ? ' ' : $to;
$result = @mail($to, $this->subject, preg_replace("#(?<!\r)\n#s", "\n", $this->msg), $this->extra_headers);
}
// Did it work?
if (!$result) {
bb_die('Failed sending email :: ' . (($this->use_smtp) ? 'SMTP' : 'PHP') . ' :: ' . $result);
}
return true;
}
public function encode($str)
{
if ($this->encoding == '') {
return $str;
}
// define start delimimter, end delimiter and spacer
$start = "=?$this->encoding?B?";
$end = "?=";
// encode the string and split it into chunks with spacers after each chunk
$str = base64_encode($str);
return $start . $str . $end;
}
}

View file

@ -331,9 +331,6 @@ function user_notification($mode, &$post_data, &$topic_title, &$forum_id, &$topi
");
if ($watch_list) {
require CLASS_DIR . '/emailer.php';
$emailer = new emailer($bb_cfg['smtp_delivery']);
$orig_word = $replacement_word = array();
obtain_word_list($orig_word, $replacement_word);
@ -345,10 +342,14 @@ function user_notification($mode, &$post_data, &$topic_title, &$forum_id, &$topi
$unwatch_topic = make_url(TOPIC_URL . "$topic_id&unwatch=topic");
foreach ($watch_list as $row) {
$emailer->from($bb_cfg['sitename'] . " <{$bb_cfg['board_email']}>");
$emailer->email_address($row['username'] . " <{$row['user_email']}>");
$emailer->use_template('topic_notify', $row['user_lang']);
/** @var TorrentPier\Legacy\Emailer() $emailer */
$emailer = new TorrentPier\Legacy\Emailer();
$emailer->set_from([$bb_cfg['board_email'] => $bb_cfg['sitename']]);
$emailer->set_to([$row['user_email'] => $row['username']]);
$emailer->set_subject(sprintf($lang['EMAILER_SUBJECT']['TOPIC_NOTIFY'], $topic_title));
$emailer->set_template('topic_notify', $row['user_lang']);
$emailer->assign_vars(array(
'TOPIC_TITLE' => html_entity_decode($topic_title),
'SITENAME' => $bb_cfg['sitename'],
@ -358,7 +359,6 @@ function user_notification($mode, &$post_data, &$topic_title, &$forum_id, &$topi
));
$emailer->send();
$emailer->reset();
$update_watched_sql[] = $row['user_id'];
}

View file

@ -1,188 +0,0 @@
<?php
/**
* MIT License
*
* Copyright (c) 2005-2017 TorrentPier
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
if (!defined('BB_ROOT')) {
die(basename(__FILE__));
}
define('SMTP_INCLUDED', 1);
function server_parse($socket, $response, $line = __LINE__)
{
$server_response = '';
while ($server_response[3] != ' ') {
if (!($server_response = fgets($socket, 256))) {
bb_die('Could not get mail server response codes');
}
}
if (!(substr($server_response, 0, 3) == $response)) {
bb_die('Ran into problems sending mail. Response: ' . $server_response);
}
}
// Replacement or substitute for PHP's mail command
function smtpmail($mail_to, $subject, $message, $headers = '')
{
global $bb_cfg;
// Fix any bare linefeeds in the message to make it RFC821 Compliant.
$message = preg_replace("#(?<!\r)\n#si", "\r\n", $message);
if ($headers != '') {
if (is_array($headers)) {
if (count($headers) > 1) {
$headers = implode("\n", $headers);
} else {
$headers = $headers[0];
}
}
$headers = rtrim($headers);
// Make sure there are no bare linefeeds in the headers
$headers = preg_replace('#(?<!\r)\n#si', "\r\n", $headers);
// Ok this is rather confusing all things considered,
// but we have to grab bcc and cc headers and treat them differently
// Something we really didn't take into consideration originally
$header_array = explode("\r\n", $headers);
@reset($header_array);
$headers = $cc = $bcc = '';
foreach ($header_array as $header) {
if (preg_match('#^cc:#si', $header)) {
$cc = preg_replace('#^cc:(.*)#si', '\1', $header);
} elseif (preg_match('#^bcc:#si', $header)) {
$bcc = preg_replace('#^bcc:(.*)#si', '\1', $header);
$header = '';
}
$headers .= ($header != '') ? $header . "\r\n" : '';
}
$headers = rtrim($headers);
$cc = explode(', ', $cc);
$bcc = explode(', ', $bcc);
}
if (trim($subject) == '') {
bb_die('No email subject specified');
}
if (trim($message) == '') {
bb_die('Email message was blank');
}
// Ok we have error checked as much as we can to this point let's get on it already
$ssl = ($bb_cfg['smtp_ssl']) ? 'ssl://' : '';
if (!$socket = @fsockopen($ssl . $bb_cfg['smtp_host'], $bb_cfg['smtp_port'], $errno, $errstr, 20)) {
bb_die('Could not connect to smtp host : ' . $errno . ' : ' . $errstr);
}
// Wait for reply
server_parse($socket, "220", __LINE__);
// Do we want to use AUTH?, send RFC2554 EHLO, else send RFC821 HELO
// This improved as provided by SirSir to accomodate
if (!empty($bb_cfg['smtp_username']) && !empty($bb_cfg['smtp_password'])) {
fwrite($socket, "EHLO " . $bb_cfg['smtp_host'] . "\r\n");
server_parse($socket, "250", __LINE__);
fwrite($socket, "AUTH LOGIN\r\n");
server_parse($socket, "334", __LINE__);
fwrite($socket, base64_encode($bb_cfg['smtp_username']) . "\r\n");
server_parse($socket, "334", __LINE__);
fwrite($socket, base64_encode($bb_cfg['smtp_password']) . "\r\n");
server_parse($socket, "235", __LINE__);
} else {
fwrite($socket, "HELO " . $bb_cfg['smtp_host'] . "\r\n");
server_parse($socket, "250", __LINE__);
}
// From this point onward most server response codes should be 250
// Specify who the mail is from....
fwrite($socket, "MAIL FROM: <" . $bb_cfg['board_email'] . ">\r\n");
server_parse($socket, "250", __LINE__);
// Add an additional bit of error checking to the To field.
$mail_to = (trim($mail_to) == '') ? 'Undisclosed-recipients:;' : trim($mail_to);
if (preg_match('#[^ ]+\@[^ ]+#', $mail_to)) {
fwrite($socket, "RCPT TO: <$mail_to>\r\n");
server_parse($socket, "250", __LINE__);
}
if (!empty($bcc)) {
reset($bcc);
foreach ($bcc as $bcc_address) {
// Add an additional bit of error checking to bcc header...
$bcc_address = trim($bcc_address);
if (preg_match('#[^ ]+\@[^ ]+#', $bcc_address)) {
fwrite($socket, "RCPT TO: <$bcc_address>\r\n");
server_parse($socket, "250", __LINE__);
}
}
}
if (!empty($cc)) {
reset($cc);
foreach ($cc as $cc_address) {
// Add an additional bit of error checking to cc header
$cc_address = trim($cc_address);
if (preg_match('#[^ ]+\@[^ ]+#', $cc_address)) {
fwrite($socket, "RCPT TO: <$cc_address>\r\n");
server_parse($socket, "250", __LINE__);
}
}
}
// Ok now we tell the server we are ready to start sending data
fwrite($socket, "DATA\r\n");
// This is the last response code we look for until the end of the message.
server_parse($socket, "354", __LINE__);
// Send the Subject Line...
fwrite($socket, "Subject: $subject\r\n");
// Now the To Header.
fwrite($socket, "To: $mail_to\r\n");
// Now any custom headers....
fwrite($socket, "$headers\r\n\r\n");
// Ok now we are ready for the message...
fwrite($socket, "$message\r\n");
// Ok the all the ingredients are mixed in let's cook this puppy...
fwrite($socket, ".\r\n");
server_parse($socket, "250", __LINE__);
// Now tell the server we are done and close the socket...
fwrite($socket, "QUIT\r\n");
fclose($socket);
return true;
}

View file

@ -56,54 +56,49 @@ if ($row = DB()->fetch_row($sql)) {
$user_email = $row['user_email'];
$user_lang = $row['user_lang'];
if (true || IS_ADMIN) {
// TRUE instead of missing user_opt "prevent_email"
if (isset($_POST['submit'])) {
$subject = trim(html_entity_decode($_POST['subject']));
$message = trim(html_entity_decode($_POST['message']));
if (isset($_POST['submit'])) {
$subject = trim(html_entity_decode($_POST['subject']));
$message = trim(html_entity_decode($_POST['message']));
if (!$subject) {
$errors[] = $lang['EMPTY_SUBJECT_EMAIL'];
}
if (!$message) {
$errors[] = $lang['EMPTY_MESSAGE_EMAIL'];
}
if (!$errors) {
require CLASS_DIR . '/emailer.php';
$emailer = new emailer($bb_cfg['smtp_delivery']);
$emailer->from($userdata['username'] . " <{$userdata['user_email']}>");
$emailer->email_address($username . " <$user_email>");
$emailer->use_template('profile_send_email', $user_lang);
$emailer->set_subject($subject);
$emailer->assign_vars(array(
'SITENAME' => $bb_cfg['sitename'],
'FROM_USERNAME' => $userdata['username'],
'TO_USERNAME' => $username,
'MESSAGE' => $message,
));
$emailer->send();
$emailer->reset();
bb_die($lang['EMAIL_SENT']);
}
if (!$subject) {
$errors[] = $lang['EMPTY_SUBJECT_EMAIL'];
}
if (!$message) {
$errors[] = $lang['EMPTY_MESSAGE_EMAIL'];
}
$template->assign_vars(array(
'USERNAME' => profile_url($row),
'S_HIDDEN_FIELDS' => '',
'S_POST_ACTION' => "profile.php?mode=email&amp;" . POST_USERS_URL . "=$user_id",
'ERROR_MESSAGE' => ($errors) ? implode('<br />', array_unique($errors)) : '',
));
if (!$errors) {
/** @var TorrentPier\Legacy\Emailer() $emailer */
$emailer = new TorrentPier\Legacy\Emailer();
print_page('usercp_email.tpl');
} else {
bb_die($lang['USER_PREVENT_EMAIL']);
$emailer->set_from([$userdata['user_email'] => $userdata['username']]);
$emailer->set_to([$user_email => $username]);
$emailer->set_subject($subject);
$emailer->set_template('profile_send_email', $user_lang);
$emailer->assign_vars(array(
'SITENAME' => $bb_cfg['sitename'],
'FROM_USERNAME' => $userdata['username'],
'TO_USERNAME' => $username,
'MESSAGE' => $message,
));
$emailer->send();
bb_die($lang['EMAIL_SENT']);
}
}
$template->assign_vars(array(
'USERNAME' => profile_url($row),
'S_HIDDEN_FIELDS' => '',
'S_POST_ACTION' => "profile.php?mode=email&amp;" . POST_USERS_URL . "=$user_id",
'ERROR_MESSAGE' => ($errors) ? implode('<br />', array_unique($errors)) : '',
));
print_page('usercp_email.tpl');
} else {
bb_die($lang['USER_NOT_EXIST']);
}

View file

@ -584,31 +584,31 @@ if ($submit && !$errors) {
} else {
if ($bb_cfg['reg_email_activation']) {
$message = $lang['ACCOUNT_INACTIVE'];
$email_subject = sprintf($lang['EMAILER_SUBJECT']['USER_WELCOME_INACTIVE'], $bb_cfg['sitename']);
$email_template = 'user_welcome_inactive';
} else {
$message = $lang['ACCOUNT_ADDED'];
$email_subject = sprintf($lang['EMAILER_SUBJECT']['USER_WELCOME'], $bb_cfg['sitename']);
$email_template = 'user_welcome';
}
require CLASS_DIR . '/emailer.php';
$emailer = new emailer($bb_cfg['smtp_delivery']);
/** @var TorrentPier\Legacy\Emailer() $emailer */
$emailer = new TorrentPier\Legacy\Emailer();
$emailer->from($bb_cfg['sitename'] . " <{$bb_cfg['board_email']}>");
$emailer->email_address($username . " <{$email}>");
$emailer->use_template($email_template, $user_lang);
$emailer->set_from([$bb_cfg['board_email'] => $bb_cfg['sitename']]);
$emailer->set_to([$email => $username]);
$emailer->set_subject($email_subject);
$emailer->set_template($email_template, $user_lang);
$emailer->assign_vars(array(
'SITENAME' => $bb_cfg['sitename'],
'WELCOME_MSG' => sprintf($lang['WELCOME_SUBJECT'], $bb_cfg['sitename']),
'USERNAME' => html_entity_decode($username),
'PASSWORD' => $new_pass,
'U_ACTIVATE' => make_url('profile.php?mode=activate&' . POST_USERS_URL . '=' . $new_user_id . '&act_key=' . $db_data['user_actkey'])
));
$emailer->send();
$emailer->reset();
}
bb_die($message);
@ -625,21 +625,22 @@ if ($submit && !$errors) {
$pr_data['user_actkey'] = $user_actkey;
$db_data['user_actkey'] = $user_actkey;
require CLASS_DIR . '/emailer.php';
$emailer = new emailer($bb_cfg['smtp_delivery']);
/** @var TorrentPier\Legacy\Emailer() $emailer */
$emailer = new TorrentPier\Legacy\Emailer();
$emailer->from($bb_cfg['sitename'] . " <{$bb_cfg['board_email']}>");
$emailer->email_address($username . " <{$email}>");
$emailer->use_template('user_activate', $pr_data['user_lang']);
$emailer->set_from([$bb_cfg['board_email'] => $bb_cfg['sitename']]);
$emailer->set_to([$email => $username]);
$emailer->set_subject($subject);
$emailer->set_subject($lang['EMAILER_SUBJECT']['USER_ACTIVATE']);
$emailer->set_template('user_activate', $pr_data['user_lang']);
$emailer->assign_vars(array(
'SITENAME' => $bb_cfg['sitename'],
'USERNAME' => html_entity_decode($username),
'U_ACTIVATE' => make_url("profile.php?mode=activate&u={$pr_data['user_id']}&act_key=$user_actkey"),
));
$emailer->send();
$emailer->reset();
$message = $lang['PROFILE_UPDATED_INACTIVE'];
$user->session_end();

View file

@ -63,22 +63,22 @@ if (isset($_POST['submit'])) {
bb_die('Could not update new password information');
}
require CLASS_DIR . '/emailer.php';
$emailer = new emailer($bb_cfg['smtp_delivery']);
/** @var TorrentPier\Legacy\Emailer() $emailer */
$emailer = new TorrentPier\Legacy\Emailer();
$emailer->from($bb_cfg['sitename'] . " <{$bb_cfg['board_email']}>");
$emailer->email_address("$username <{$row['user_email']}>");
$emailer->use_template('user_activate_passwd', $row['user_lang']);
$emailer->set_from([$bb_cfg['board_email'] => $bb_cfg['sitename']]);
$emailer->set_to([$row['user_email'] => $username]);
$emailer->set_subject($lang['EMAILER_SUBJECT']['USER_ACTIVATE_PASSWD']);
$emailer->set_template('user_activate_passwd', $row['user_lang']);
$emailer->assign_vars(array(
'SITENAME' => $bb_cfg['sitename'],
'USERNAME' => $username,
'PASSWORD' => $user_password,
'U_ACTIVATE' => make_url('profile.php?mode=activate&' . POST_USERS_URL . '=' . $user_id . '&act_key=' . $user_actkey)
));
$emailer->send();
$emailer->reset();
bb_die($lang['PASSWORD_UPDATED']);
} else {

View file

@ -929,14 +929,14 @@ if ($mode == 'read') {
cache_rm_user_sessions($to_userdata['user_id']);
if (bf($to_userdata['user_opt'], 'user_opt', 'user_notify_pm') && $to_userdata['user_active'] && $bb_cfg['pm_notify_enabled']) {
require CLASS_DIR . '/emailer.php';
$emailer = new emailer($bb_cfg['smtp_delivery']);
/** @var TorrentPier\Legacy\Emailer() $emailer */
$emailer = new TorrentPier\Legacy\Emailer();
$emailer->from($bb_cfg['sitename'] . " <{$bb_cfg['board_email']}>");
$emailer->email_address($to_userdata['username'] . " <{$to_userdata['user_email']}>");
$emailer->use_template('privmsg_notify', $to_userdata['user_lang']);
$emailer->set_from([$bb_cfg['board_email'] => $bb_cfg['sitename']]);
$emailer->set_to([$to_userdata['user_email'] => $to_userdata['username']]);
$emailer->set_subject($lang['EMAILER_SUBJECT']['PRIVMSG_NOTIFY']);
$emailer->set_template('privmsg_notify', $to_userdata['user_lang']);
$emailer->assign_vars(array(
'USERNAME' => html_entity_decode($to_username),
'NAME_FROM' => $userdata['username'],
@ -946,7 +946,6 @@ if ($mode == 'read') {
));
$emailer->send();
$emailer->reset();
}
}

279
src/Legacy/Emailer.php Normal file
View file

@ -0,0 +1,279 @@
<?php
/**
* MIT License
*
* Copyright (c) 2005-2017 TorrentPier
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
namespace TorrentPier\Legacy;
use Swift_Mailer;
use Swift_Message;
use Swift_SendmailTransport;
use Swift_SmtpTransport;
/**
* Имплементация старого класса Emailer с заменой отправки на SwiftMailer
* Переписать при дальнейшем переходе проекта на контейнерную структуру
*
* Class Emailer
* @package TorrentPier\Legacy
*/
class Emailer
{
/**
* Обычное текстовое сообщение
*/
const FORMAT_TEXT = 'text/plain';
/**
* HTML-сообщение
*/
const FORMAT_HTML = 'text/html';
/** @var string текст сообщения */
private $message;
/** @var string тема сообщения */
private $subject;
/** @var string адрес получателя */
private $to;
/** @var string адрес отправителя */
private $from;
/** @var string адрес для ответа */
private $reply;
/** @var string адрес копии */
private $cc;
/** @var array шаблон письма с указанием языка */
private $tpl_msg = [];
/** @var array переменные, подменяемые в шаблонах писем */
private $vars = [];
/** @var string кодировка отправляемых сообщений */
private $encoding;
public function __construct()
{
global $bb_cfg;
$this->reply = $bb_cfg['board_email'];
}
/**
* Установка темы сообщения
*
* @param string $subject
*/
public function set_subject($subject)
{
$this->subject = $subject;
}
/**
* Установка адреса получателя
*
* @param $address
*/
public function set_to($address)
{
$this->to = $address;
}
/**
* Установка адреса отправителя
*
* @param $address
*/
public function set_from($address)
{
$this->from = $address;
}
/**
* Установка адреса для ответа
*
* @param $address
*/
public function set_reply($address)
{
$this->reply = $address;
}
/**
* Установка адреса для копии
*
* @param $address
*/
public function set_cc($address)
{
$this->cc = $address;
}
/**
* Установка шаблона сообщения
*
* @param string $template_file имя шаблона
* @param string $template_lang язык шаблона
*/
public function set_template($template_file, $template_lang = '')
{
global $bb_cfg;
if (!$template_lang) {
$template_lang = $bb_cfg['default_lang'];
}
if (empty($this->tpl_msg[$template_lang . $template_file])) {
$tpl_file = LANG_ROOT_DIR . '/' . $template_lang . '/email/' . $template_file . '.html';
if (!file_exists($tpl_file)) {
$tpl_file = LANG_ROOT_DIR . '/' . $bb_cfg['default_lang'] . '/email/' . $template_file . '.html';
/** @noinspection NotOptimalIfConditionsInspection */
if (!file_exists($tpl_file)) {
bb_die('Could not find email template file: ' . $template_file);
}
}
if (!$fd = fopen($tpl_file, 'rb')) {
bb_die('Failed opening email template file: ' . $tpl_file);
}
$this->tpl_msg[$template_lang . $template_file] = fread($fd, filesize($tpl_file));
fclose($fd);
}
$this->message = $this->tpl_msg[$template_lang . $template_file];
}
/**
* Отправка сообщения получателям через SwiftMailer
*
* @param string $email_format
* @return bool
*/
public function send($email_format = self::FORMAT_TEXT)
{
global $bb_cfg, $lang, $userdata;
if (!$bb_cfg['emailer']['enabled']) {
return false;
}
/**
* Escape message and set vars
*/
$this->message = str_replace("'", "\'", $this->message);
$this->message = preg_replace('#\{([a-z0-9\-_]*?)\}#is', "' . $\\1 . '", $this->message);
foreach ($this->vars as $key => $val) {
$this->message = preg_replace(sprintf('/\$\{?%s\}?/', $key), $val, $this->message);
}
/** Set some variables */
$this->subject = !empty($this->subject) ? $this->subject : $lang['EMAILER_SUBJECT']['EMPTY'];
$this->encoding = $bb_cfg['lang'][$userdata['user_lang']]['encoding'];
/** Prepare message */
if ($bb_cfg['emailer']['smtp']['enabled']) {
if (!empty($bb_cfg['emailer']['smtp']['host'])) {
if (empty($bb_cfg['emailer']['ssl_type'])) {
/** @var Swift_SmtpTransport $transport external SMTP without ssl */
$transport = (new Swift_SmtpTransport(
$bb_cfg['emailer']['smtp']['host'],
$bb_cfg['emailer']['smtp']['port']
))
->setUsername($bb_cfg['emailer']['smtp']['username'])
->setPassword($bb_cfg['emailer']['smtp']['password']);
} else {
/** @var Swift_SmtpTransport $transport external SMTP with ssl */
$transport = (new Swift_SmtpTransport(
$bb_cfg['emailer']['smtp']['host'],
$bb_cfg['emailer']['smtp']['port'],
$bb_cfg['emailer']['ssl_type']
))
->setUsername($bb_cfg['emailer']['smtp']['username'])
->setPassword($bb_cfg['emailer']['smtp']['password']);
}
} else {
/** @var Swift_SmtpTransport $transport local SMTP */
$transport = new Swift_SmtpTransport('localhost', 25);
}
} else {
/** @var Swift_SendmailTransport $transport local SendMail */
$transport = new Swift_SendmailTransport('/usr/sbin/sendmail -bs');
}
/** @var Swift_Mailer $mailer */
$mailer = new Swift_Mailer($transport);
/** @var Swift_Message $message */
$message = (new Swift_Message())
->setSubject($this->subject)
->setReturnPath($bb_cfg['board_email'])
->setFrom($this->from)
->setTo($this->to)
->setReplyTo($this->reply)
->setBody($this->message, $email_format)
->setCharset($this->encoding);
if (!empty($this->cc)) {
$message->setCc($this->cc);
}
/** Send message */
if (!$result = $mailer->send($message)) {
bb_die('Failed sending email: ' . $result);
}
return true;
}
/**
* Установка переменных шаблона сообщения
*
* @param $vars
*/
public function assign_vars($vars)
{
$this->set_default_vars();
$this->vars = array_merge($this->vars, $vars);
}
/**
* Задание стандартных переменных шаблонов сообщения
*/
public function set_default_vars()
{
global $bb_cfg;
$this->vars = [
'BOARD_EMAIL' => $bb_cfg['board_email'],
'SITENAME' => $bb_cfg['board_email_sitename'],
'EMAIL_SIG' => !empty($bb_cfg['board_email_sig']) ? "-- \n{$bb_cfg['board_email_sig']}" : '',
];
}
}