Merge pull request #8176 from nupplaphil/task/split_emails

Prepare Model\Notify for include/enotify.php (Part 3)
This commit is contained in:
Hypolite Petovan 2020-01-26 17:02:14 -05:00 committed by GitHub
commit df61be84fc
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
7 changed files with 386 additions and 152 deletions

View File

@ -15,9 +15,8 @@ use Friendica\Model\ItemContent;
use Friendica\Model\Notify;
use Friendica\Model\User;
use Friendica\Model\UserItem;
use Friendica\Object\Email;
use Friendica\Protocol\Activity;
use Friendica\Util\DateTimeFormat;
use Friendica\Util\Emailer;
/**
* Creates a notification entry and possibly sends a mail
@ -512,19 +511,19 @@ function notification($params)
Logger::log('sending notification email');
if (isset($params['parent']) && (intval($params['parent']) != 0)) {
$id_for_parent = $params['parent']."@".$hostname;
$id_for_parent = $params['parent'] . "@" . $hostname;
// Is this the first email notification for this parent item and user?
if (!DBA::exists('notify-threads', ['master-parent-item' => $params['parent'], 'receiver-uid' => $params['uid']])) {
Logger::log("notify_id:".intval($notify_id).", parent: ".intval($params['parent'])."uid: ".intval($params['uid']), Logger::DEBUG);
Logger::log("notify_id:" . intval($notify_id) . ", parent: " . intval($params['parent']) . "uid: " . intval($params['uid']), Logger::DEBUG);
$fields = ['notify-id' => $notify_id, 'master-parent-item' => $params['parent'],
'receiver-uid' => $params['uid'], 'parent-item' => 0];
$fields = ['notify-id' => $notify_id, 'master-parent-item' => $params['parent'],
'receiver-uid' => $params['uid'], 'parent-item' => 0];
DBA::insert('notify-threads', $fields);
$additional_mail_header .= "Message-ID: <${id_for_parent}>\n";
$log_msg = "include/enotify: No previous notification found for this parent:\n".
" parent: ${params['parent']}\n"." uid : ${params['uid']}\n";
$log_msg = "include/enotify: No previous notification found for this parent:\n" .
" parent: ${params['parent']}\n" . " uid : ${params['uid']}\n";
Logger::log($log_msg, Logger::DEBUG);
} else {
// If not, just "follow" the thread.
@ -536,30 +535,30 @@ function notification($params)
$textversion = BBCode::toPlaintext($body);
$htmlversion = BBCode::convert($body);
$datarray = [];
$datarray['banner'] = $banner;
$datarray['product'] = $product;
$datarray['preamble'] = $preamble;
$datarray['sitename'] = $sitename;
$datarray['siteurl'] = $siteurl;
$datarray['type'] = $params['type'];
$datarray['parent'] = $parent_id;
$datarray['source_name'] = $params['source_name'] ?? '';
$datarray['source_link'] = $params['source_link'] ?? '';
$datarray = [];
$datarray['banner'] = $banner;
$datarray['product'] = $product;
$datarray['preamble'] = $preamble;
$datarray['sitename'] = $sitename;
$datarray['siteurl'] = $siteurl;
$datarray['type'] = $params['type'];
$datarray['parent'] = $parent_id;
$datarray['source_name'] = $params['source_name'] ?? '';
$datarray['source_link'] = $params['source_link'] ?? '';
$datarray['source_photo'] = $params['source_photo'] ?? '';
$datarray['uid'] = $params['uid'];
$datarray['username'] = $params['to_name'] ?? '';
$datarray['hsitelink'] = $hsitelink;
$datarray['tsitelink'] = $tsitelink;
$datarray['hitemlink'] = '<a href="'.$itemlink.'">'.$itemlink.'</a>';
$datarray['titemlink'] = $itemlink;
$datarray['thanks'] = $thanks;
$datarray['site_admin'] = $site_admin;
$datarray['title'] = stripslashes($title);
$datarray['htmlversion'] = $htmlversion;
$datarray['textversion'] = $textversion;
$datarray['subject'] = $subject;
$datarray['headers'] = $additional_mail_header;
$datarray['uid'] = $params['uid'];
$datarray['username'] = $params['to_name'] ?? '';
$datarray['hsitelink'] = $hsitelink;
$datarray['tsitelink'] = $tsitelink;
$datarray['hitemlink'] = '<a href="' . $itemlink . '">' . $itemlink . '</a>';
$datarray['titemlink'] = $itemlink;
$datarray['thanks'] = $thanks;
$datarray['site_admin'] = $site_admin;
$datarray['title'] = stripslashes($title);
$datarray['htmlversion'] = $htmlversion;
$datarray['textversion'] = $textversion;
$datarray['subject'] = $subject;
$datarray['headers'] = $additional_mail_header;
Hook::callAll('enotify_mail', $datarray);
@ -568,59 +567,53 @@ function notification($params)
$content_allowed = ((!DI::config()->get('system', 'enotify_no_content')) || ($params['type'] == SYSTEM_EMAIL));
// load the template for private message notifications
$tpl = Renderer::getMarkupTemplate('email_notify_html.tpl');
$tpl = Renderer::getMarkupTemplate('email_notify_html.tpl');
$email_html_body = Renderer::replaceMacros($tpl, [
'$banner' => $datarray['banner'],
'$product' => $datarray['product'],
'$preamble' => str_replace("\n", "<br>\n", $datarray['preamble']),
'$sitename' => $datarray['sitename'],
'$siteurl' => $datarray['siteurl'],
'$source_name' => $datarray['source_name'],
'$source_link' => $datarray['source_link'],
'$source_photo' => $datarray['source_photo'],
'$username' => $datarray['username'],
'$hsitelink' => $datarray['hsitelink'],
'$hitemlink' => $datarray['hitemlink'],
'$thanks' => $datarray['thanks'],
'$site_admin' => $datarray['site_admin'],
'$title' => $datarray['title'],
'$htmlversion' => $datarray['htmlversion'],
'$content_allowed' => $content_allowed,
'$banner' => $datarray['banner'],
'$product' => $datarray['product'],
'$preamble' => str_replace("\n", "<br>\n", $datarray['preamble']),
'$sitename' => $datarray['sitename'],
'$siteurl' => $datarray['siteurl'],
'$source_name' => $datarray['source_name'],
'$source_link' => $datarray['source_link'],
'$source_photo' => $datarray['source_photo'],
'$username' => $datarray['username'],
'$hsitelink' => $datarray['hsitelink'],
'$hitemlink' => $datarray['hitemlink'],
'$thanks' => $datarray['thanks'],
'$site_admin' => $datarray['site_admin'],
'$title' => $datarray['title'],
'$htmlversion' => $datarray['htmlversion'],
'$content_allowed' => $content_allowed,
]);
// load the template for private message notifications
$tpl = Renderer::getMarkupTemplate('email_notify_text.tpl');
$tpl = Renderer::getMarkupTemplate('email_notify_text.tpl');
$email_text_body = Renderer::replaceMacros($tpl, [
'$banner' => $datarray['banner'],
'$product' => $datarray['product'],
'$preamble' => $datarray['preamble'],
'$sitename' => $datarray['sitename'],
'$siteurl' => $datarray['siteurl'],
'$source_name' => $datarray['source_name'],
'$source_link' => $datarray['source_link'],
'$source_photo' => $datarray['source_photo'],
'$username' => $datarray['username'],
'$tsitelink' => $datarray['tsitelink'],
'$titemlink' => $datarray['titemlink'],
'$thanks' => $datarray['thanks'],
'$site_admin' => $datarray['site_admin'],
'$title' => $datarray['title'],
'$textversion' => $datarray['textversion'],
'$content_allowed' => $content_allowed,
'$banner' => $datarray['banner'],
'$product' => $datarray['product'],
'$preamble' => $datarray['preamble'],
'$sitename' => $datarray['sitename'],
'$siteurl' => $datarray['siteurl'],
'$source_name' => $datarray['source_name'],
'$source_link' => $datarray['source_link'],
'$source_photo' => $datarray['source_photo'],
'$username' => $datarray['username'],
'$tsitelink' => $datarray['tsitelink'],
'$titemlink' => $datarray['titemlink'],
'$thanks' => $datarray['thanks'],
'$site_admin' => $datarray['site_admin'],
'$title' => $datarray['title'],
'$textversion' => $datarray['textversion'],
'$content_allowed' => $content_allowed,
]);
$email = new Email($sender_name, $sender_email, $sender_email, $params['to_email'],
$datarray['subject'], $email_html_body, $email_text_body,
$datarray['headers'], $params['uid']);
// use the Emailer class to send the message
return Emailer::send([
'uid' => $params['uid'],
'fromName' => $sender_name,
'fromEmail' => $sender_email,
'replyTo' => $sender_email,
'toEmail' => $params['to_email'],
'messageSubject' => $datarray['subject'],
'htmlVersion' => $email_html_body,
'textVersion' => $email_text_body,
'additionalMailHeader' => $datarray['headers']
]);
return DI::emailer()->send($email);
}
return false;

View File

@ -18,7 +18,6 @@
use Friendica\App;
use Friendica\Content\Pager;
use Friendica\Content\Text\BBCode;
use Friendica\Content\Text\HTML;
use Friendica\Core\Hook;
use Friendica\Core\Logger;
use Friendica\Core\Protocol;
@ -34,11 +33,10 @@ use Friendica\Model\FileTag;
use Friendica\Model\Item;
use Friendica\Model\Photo;
use Friendica\Model\Term;
use Friendica\Object\EMail\ItemCCEMail;
use Friendica\Protocol\Activity;
use Friendica\Protocol\Diaspora;
use Friendica\Protocol\Email;
use Friendica\Util\DateTimeFormat;
use Friendica\Util\Emailer;
use Friendica\Util\Security;
use Friendica\Util\Strings;
use Friendica\Worker\Delivery;
@ -788,35 +786,15 @@ function item_post(App $a) {
Hook::callAll('post_local_end', $datarray);
if (strlen($emailcc) && $profile_uid == local_user()) {
$erecips = explode(',', $emailcc);
if (count($erecips)) {
foreach ($erecips as $recip) {
$addr = trim($recip);
if (!strlen($addr)) {
$recipients = explode(',', $emailcc);
if (count($recipients)) {
foreach ($recipients as $recipient) {
$address = trim($recipient);
if (!strlen($address)) {
continue;
}
$disclaimer = '<hr />' . DI::l10n()->t('This message was sent to you by %s, a member of the Friendica social network.', $a->user['username'])
. '<br />';
$disclaimer .= DI::l10n()->t('You may visit them online at %s', DI::baseUrl() . '/profile/' . $a->user['nickname']) . EOL;
$disclaimer .= DI::l10n()->t('Please contact the sender by replying to this post if you do not wish to receive these messages.') . EOL;
if (!$datarray['title']=='') {
$subject = Email::encodeHeader($datarray['title'], 'UTF-8');
} else {
$subject = Email::encodeHeader('[Friendica]' . ' ' . DI::l10n()->t('%s posted an update.', $a->user['username']), 'UTF-8');
}
$link = '<a href="' . DI::baseUrl() . '/profile/' . $a->user['nickname'] . '"><img src="' . $author['thumb'] . '" alt="' . $a->user['username'] . '" /></a><br /><br />';
$html = Item::prepareBody($datarray);
$message = '<html><body>' . $link . $html . $disclaimer . '</body></html>';
$params = [
'fromName' => $a->user['username'],
'fromEmail' => $a->user['email'],
'toEmail' => $addr,
'replyTo' => $a->user['email'],
'messageSubject' => $subject,
'htmlVersion' => $message,
'textVersion' => HTML::toPlaintext($html.$disclaimer)
];
Emailer::send($params);
DI::emailer()->send(new ItemCCEMail(DI::app(), DI::l10n(), DI::baseUrl(),
$datarray, $address, $author['thumb'] ?? ''));
}
}
}

View File

@ -363,4 +363,12 @@ abstract class DI
{
return self::$dice->create(Util\Profiler::class);
}
/**
* @return Util\Emailer
*/
public static function emailer()
{
return self::$dice->create(Util\Emailer::class);
}
}

View File

@ -0,0 +1,71 @@
<?php
namespace Friendica\Object\EMail;
use Friendica\Util\Emailer;
/**
* Interface for a single mail, which can be send through Emailer::send()
*
* @see Emailer::send()
*/
interface IEmail
{
/**
* Gets the senders name for this email
*
* @return string
*/
function getFromName();
/**
* Gets the senders email address for this email
*
* @return string
*/
function getFromAddress();
/**
* Gets the UID of the sender of this email
*
* @return int|null
*/
function getRecipientUid();
/**
* Gets the reply-to address for this email
*
* @return string
*/
function getReplyTo();
/**
* Gets the senders email address
*
* @return string
*/
function getToAddress();
/**
* Gets the subject of this email
*
* @return string
*/
function getSubject();
/**
* Gets the message body of this email (either html or plaintext)
*
* @param boolean $plain True, if returned as plaintext
*
* @return string
*/
function getMessage(bool $plain = false);
/**
* Gets any additional mail header
*
* @return string
*/
function getAdditionalMailHeader();
}

View File

@ -0,0 +1,35 @@
<?php
namespace Friendica\Object\EMail;
use Friendica\App;
use Friendica\App\BaseURL;
use Friendica\Content\Text\HTML;
use Friendica\Core\L10n;
use Friendica\Model\Item;
use Friendica\Object\Email;
/**
* Class for creating CC emails based on a received item
*/
class ItemCCEMail extends Email
{
public function __construct(App $a, L10n $l10n, BaseURL $baseUrl, array $item, string $toAddress, string $authorThumb)
{
$disclaimer = '<hr />' . $l10n->t('This message was sent to you by %s, a member of the Friendica social network.', $a->user['username'])
. '<br />';
$disclaimer .= $l10n->t('You may visit them online at %s', $baseUrl . '/profile/' . $a->user['nickname']) . EOL;
$disclaimer .= $l10n->t('Please contact the sender by replying to this post if you do not wish to receive these messages.') . EOL;
if (!$item['title'] == '') {
$subject = Email::encodeHeader($item['title'], 'UTF-8');
} else {
$subject = Email::encodeHeader('[Friendica]' . ' ' . $l10n->t('%s posted an update.', $a->user['username']), 'UTF-8');
}
$link = '<a href="' . $baseUrl . '/profile/' . $a->user['nickname'] . '"><img src="' . $authorThumb . '" alt="' . $a->user['username'] . '" /></a><br /><br />';
$html = Item::prepareBody($item);
$message = '<html><body>' . $link . $html . $disclaimer . '</body></html>';;
parent::__construct($a->user['username'], $a->user['email'], $a->user['email'], $toAddress,
$subject, $message, HTML::toPlaintext($html . $disclaimer));
}
}

135
src/Object/Email.php Normal file
View File

@ -0,0 +1,135 @@
<?php
namespace Friendica\Object;
use Friendica\Object\EMail\IEmail;
/**
* The default implementation of the IEmail interface
*
* Provides the possibility to reuse the email instance with new recipients (@see Email::withRecipient())
*/
class Email implements IEmail
{
/** @var string */
private $fromName;
/** @var string */
private $fromAddress;
/** @var string */
private $replyTo;
/** @var string */
private $toAddress;
/** @var string */
private $subject;
/** @var string */
private $msgHtml;
/** @var string */
private $msgText;
/** @var string */
private $additionalMailHeader = '';
/** @var int|null */
private $toUid = null;
public function __construct(string $fromName, string $fromAddress, string $replyTo, string $toAddress,
string $subject, string $msgHtml, string $msgText,
string $additionalMailHeader = '', int $toUid = null)
{
$this->fromName = $fromName;
$this->fromAddress = $fromAddress;
$this->replyTo = $replyTo;
$this->toAddress = $toAddress;
$this->subject = $subject;
$this->msgHtml = $msgHtml;
$this->msgText = $msgText;
$this->additionalMailHeader = $additionalMailHeader;
$this->toUid = $toUid;
}
/**
* {@inheritDoc}
*/
public function getFromName()
{
return $this->fromName;
}
/**
* {@inheritDoc}
*/
public function getFromAddress()
{
return $this->fromAddress;
}
/**
* {@inheritDoc}
*/
public function getReplyTo()
{
return $this->replyTo;
}
/**
* {@inheritDoc}
*/
public function getToAddress()
{
return $this->toAddress;
}
/**
* {@inheritDoc}
*/
public function getSubject()
{
return $this->subject;
}
/**
* {@inheritDoc}
*/
public function getMessage(bool $plain = false)
{
if ($plain) {
return $this->msgText;
} else {
return $this->msgHtml;
}
}
/**
* {@inheritDoc}
*/
public function getAdditionalMailHeader()
{
return $this->additionalMailHeader;
}
/**
* {@inheritDoc}
*/
public function getRecipientUid()
{
return $this->toUid;
}
/**
* Returns the current email with a new recipient
*
* @param string $email The email of the recipient
* @param int $uid The (optional) UID of the recipient for further infos
*
* @return static
*/
public function withRecipient(string $email, int $uid = null)
{
$newEmail = clone $this;
$newEmail->toAddress = $email;
$newEmail->toUid = $uid;
return $newEmail;
}
}

View File

@ -4,34 +4,46 @@
*/
namespace Friendica\Util;
use Friendica\App;
use Friendica\Core\Config\IConfig;
use Friendica\Core\Hook;
use Friendica\Core\Logger;
use Friendica\DI;
use Friendica\Core\PConfig\IPConfig;
use Friendica\Network\HTTPException\InternalServerErrorException;
use Friendica\Object\EMail\IEmail;
use Friendica\Protocol\Email;
use Psr\Log\LoggerInterface;
/**
* class to handle emailing
*/
class Emailer
{
/** @var IConfig */
private $config;
/** @var IPConfig */
private $pConfig;
/** @var LoggerInterface */
private $logger;
/** @var App\BaseURL */
private $baseUrl;
public function __construct(IConfig $config, IPConfig $pConfig, App\BaseURL $baseURL, LoggerInterface $logger)
{
$this->config = $config;
$this->pConfig = $pConfig;
$this->logger = $logger;
$this->baseUrl = $baseURL;
}
/**
* Send a multipart/alternative message with Text and HTML versions
*
* @param array $params parameters
* fromName name of the sender
* fromEmail email of the sender
* replyTo address to direct responses
* toEmail destination email address
* messageSubject subject of the message
* htmlVersion html version of the message
* textVersion text only version of the message
* additionalMailHeader additions to the SMTP mail header
* optional uid user id of the destination user
* @param IEmail $email The email to send
*
* @return bool
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @throws InternalServerErrorException
*/
public static function send(array $params)
public function send(IEmail $email)
{
$params['sent'] = false;
@ -42,61 +54,63 @@ class Emailer
}
$email_textonly = false;
if (!empty($params['uid'])) {
$email_textonly = DI::pConfig()->get($params['uid'], "system", "email_textonly");
if (!empty($email->getRecipientUid())) {
$email_textonly = $this->pConfig->get($email->getRecipientUid(), 'system', 'email_textonly');
}
$fromName = Email::encodeHeader(html_entity_decode($params['fromName'], ENT_QUOTES, 'UTF-8'), 'UTF-8');
$messageSubject = Email::encodeHeader(html_entity_decode($params['messageSubject'], ENT_QUOTES, 'UTF-8'), 'UTF-8');
$fromName = Email::encodeHeader(html_entity_decode($email->getFromName(), ENT_QUOTES, 'UTF-8'), 'UTF-8');
$fromAddress = $email->getFromAddress();
$replyTo = $email->getReplyTo();
$messageSubject = Email::encodeHeader(html_entity_decode($email->getSubject(), ENT_QUOTES, 'UTF-8'), 'UTF-8');
// generate a mime boundary
$mimeBoundary =rand(0, 9)."-"
.rand(100000000, 999999999)."-"
.rand(100000000, 999999999)."=:"
.rand(10000, 99999);
$mimeBoundary = rand(0, 9) . '-'
. rand(100000000, 999999999) . '-'
. rand(100000000, 999999999) . '=:'
. rand(10000, 99999);
// generate a multipart/alternative message header
$messageHeader = ($params['additionalMailHeader'] ?? '') .
"From: $fromName <{$params['fromEmail']}>\n" .
"Reply-To: $fromName <{$params['replyTo']}>\n" .
"MIME-Version: 1.0\n" .
"Content-Type: multipart/alternative; boundary=\"{$mimeBoundary}\"";
$messageHeader = $email->getAdditionalMailHeader() .
"From: $fromName <{$fromAddress}>\n" .
"Reply-To: $fromName <{$replyTo}>\n" .
"MIME-Version: 1.0\n" .
"Content-Type: multipart/alternative; boundary=\"{$mimeBoundary}\"";
// assemble the final multipart message body with the text and html types included
$textBody = chunk_split(base64_encode($params['textVersion']));
$htmlBody = chunk_split(base64_encode($params['htmlVersion']));
$multipartMessageBody = "--" . $mimeBoundary . "\n" . // plain text section
"Content-Type: text/plain; charset=UTF-8\n" .
"Content-Transfer-Encoding: base64\n\n" .
$textBody . "\n";
$textBody = chunk_split(base64_encode($email->getMessage(true)));
$htmlBody = chunk_split(base64_encode($email->getMessage()));
$multipartMessageBody = "--" . $mimeBoundary . "\n" . // plain text section
"Content-Type: text/plain; charset=UTF-8\n" .
"Content-Transfer-Encoding: base64\n\n" .
$textBody . "\n";
if (!$email_textonly && !is_null($params['htmlVersion'])) {
if (!$email_textonly && !is_null($email->getMessage())) {
$multipartMessageBody .=
"--" . $mimeBoundary . "\n" . // text/html section
"--" . $mimeBoundary . "\n" . // text/html section
"Content-Type: text/html; charset=UTF-8\n" .
"Content-Transfer-Encoding: base64\n\n" .
$htmlBody . "\n";
}
$multipartMessageBody .=
"--" . $mimeBoundary . "--\n"; // message ending
"--" . $mimeBoundary . "--\n"; // message ending
if (DI::config()->get("system", "sendmail_params", true)) {
$sendmail_params = '-f ' . $params['fromEmail'];
if ($this->config->get('system', 'sendmail_params', true)) {
$sendmail_params = '-f ' . $fromAddress;
} else {
$sendmail_params = null;
}
// send the message
$hookdata = [
'to' => $params['toEmail'],
'subject' => $messageSubject,
'body' => $multipartMessageBody,
'headers' => $messageHeader,
'to' => $email->getToAddress(),
'subject' => $messageSubject,
'body' => $multipartMessageBody,
'headers' => $messageHeader,
'parameters' => $sendmail_params,
'sent' => false,
'sent' => false,
];
Hook::callAll("emailer_send", $hookdata);
Hook::callAll('emailer_send', $hookdata);
if ($hookdata['sent']) {
return true;
@ -109,8 +123,8 @@ class Emailer
$hookdata['headers'],
$hookdata['parameters']
);
Logger::log("header " . 'To: ' . $params['toEmail'] . "\n" . $messageHeader, Logger::DEBUG);
Logger::log("return value " . (($res)?"true":"false"), Logger::DEBUG);
$this->logger->debug('header ' . 'To: ' . $email->getToAddress() . '\n' . $messageHeader);
$this->logger->debug('return value ' . (($res) ? 'true' : 'false'));
return $res;
}
}