717366248f7a9f11e332c345809c99612cbd8f5c
[friendica.git/.git] / src / Util / Emailer.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2020, Friendica
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 namespace Friendica\Util;
23
24 use Friendica\App;
25 use Friendica\Core\Config\IConfig;
26 use Friendica\Core\Hook;
27 use Friendica\Core\L10n;
28 use Friendica\Core\PConfig\IPConfig;
29 use Friendica\Network\HTTPException\InternalServerErrorException;
30 use Friendica\Object\EMail\IEmail;
31 use Friendica\Protocol\Email;
32 use Friendica\Util\EMailer\NotifyMailBuilder;
33 use Friendica\Util\EMailer\SystemMailBuilder;
34 use Psr\Log\LoggerInterface;
35
36 /**
37  * class to handle emailing
38  */
39 class Emailer
40 {
41         /** @var IConfig */
42         private $config;
43         /** @var IPConfig */
44         private $pConfig;
45         /** @var LoggerInterface */
46         private $logger;
47         /** @var App\BaseURL */
48         private $baseUrl;
49         /** @var L10n */
50         private $l10n;
51
52         /** @var string */
53         private $siteEmailAddress;
54         /** @var string */
55         private $siteEmailName;
56
57         public function __construct(IConfig $config, IPConfig $pConfig, App\BaseURL $baseURL, LoggerInterface $logger,
58                                     L10n $defaultLang)
59         {
60                 $this->config      = $config;
61                 $this->pConfig     = $pConfig;
62                 $this->logger      = $logger;
63                 $this->baseUrl     = $baseURL;
64                 $this->l10n        = $defaultLang;
65
66                 $this->siteEmailAddress = $this->config->get('config', 'sender_email');
67                 if (empty($this->siteEmailAddress)) {
68                         $hostname = $this->baseUrl->getHostname();
69                         if (strpos($hostname, ':')) {
70                                 $hostname = substr($hostname, 0, strpos($hostname, ':'));
71                         }
72
73                         $this->siteEmailAddress = 'noreply@' . $hostname;
74                 }
75
76                 $this->siteEmailName = $this->config->get('config', 'sitename', 'Friendica Social Network');
77         }
78
79         /**
80          * Gets the site's default sender email address
81          *
82          * @return string
83          */
84         public function getSiteEmailAddress()
85         {
86                 return $this->siteEmailAddress;
87         }
88
89         /**
90          * Gets the site's default sender name
91          *
92          * @return string
93          */
94         public function getSiteEmailName()
95         {
96                 return $this->siteEmailName;
97         }
98
99         /**
100          * Creates a new system email
101          *
102          * @return SystemMailBuilder
103          */
104         public function newSystemMail()
105         {
106                 return new SystemMailBuilder($this->l10n, $this->baseUrl, $this->config, $this->logger,
107                         $this->getSiteEmailAddress(), $this->getSiteEmailName());
108         }
109
110         /**
111          * Creates a new mail for notifications
112          *
113          * @return NotifyMailBuilder
114          */
115         public function newNotifyMail()
116         {
117                 return new NotifyMailBuilder($this->l10n, $this->baseUrl, $this->config, $this->logger,
118                         $this->getSiteEmailAddress(), $this->getSiteEmailName());
119         }
120
121         /**
122          * Send a multipart/alternative message with Text and HTML versions
123          *
124          * @param IEmail $email The email to send
125          *
126          * @return bool
127          * @throws InternalServerErrorException
128          */
129         public function send(IEmail $email)
130         {
131                 Hook::callAll('emailer_send_prepare', $email);
132
133                 if (empty($email)) {
134                         return true;
135                 }
136
137                 $email_textonly = false;
138                 if (!empty($email->getRecipientUid())) {
139                         $email_textonly = $this->pConfig->get($email->getRecipientUid(), 'system', 'email_textonly');
140                 }
141
142                 $fromName       = Email::encodeHeader(html_entity_decode($email->getFromName(), ENT_QUOTES, 'UTF-8'), 'UTF-8');
143                 $fromAddress      = $email->getFromAddress();
144                 $replyTo        = $email->getReplyTo();
145                 $messageSubject = Email::encodeHeader(html_entity_decode($email->getSubject(), ENT_QUOTES, 'UTF-8'), 'UTF-8');
146
147                 // generate a mime boundary
148                 $mimeBoundary = rand(0, 9) . '-'
149                                 . rand(100000000, 999999999) . '-'
150                                 . rand(100000000, 999999999) . '=:'
151                                 . rand(10000, 99999);
152
153                 // generate a multipart/alternative message header
154                 $messageHeader = $email->getAdditionalMailHeader() .
155                                  "From: $fromName <{$fromAddress}>\n" .
156                                  "Reply-To: $fromName <{$replyTo}>\n" .
157                                  "MIME-Version: 1.0\n" .
158                                  "Content-Type: multipart/alternative; boundary=\"{$mimeBoundary}\"";
159
160                 // assemble the final multipart message body with the text and html types included
161                 $textBody             = chunk_split(base64_encode($email->getMessage(true)));
162                 $htmlBody             = chunk_split(base64_encode($email->getMessage()));
163                 $multipartMessageBody = "--" . $mimeBoundary . "\n" .                    // plain text section
164                                         "Content-Type: text/plain; charset=UTF-8\n" .
165                                         "Content-Transfer-Encoding: base64\n\n" .
166                                         $textBody . "\n";
167
168                 if (!$email_textonly && !is_null($email->getMessage())) {
169                         $multipartMessageBody .=
170                                 "--" . $mimeBoundary . "\n" .                // text/html section
171                                 "Content-Type: text/html; charset=UTF-8\n" .
172                                 "Content-Transfer-Encoding: base64\n\n" .
173                                 $htmlBody . "\n";
174                 }
175                 $multipartMessageBody .=
176                         "--" . $mimeBoundary . "--\n";                    // message ending
177
178                 if ($this->config->get('system', 'sendmail_params', true)) {
179                         $sendmail_params = '-f ' . $fromAddress;
180                 } else {
181                         $sendmail_params = null;
182                 }
183
184                 // send the message
185                 $hookdata = [
186                         'to'         => $email->getToAddress(),
187                         'subject'    => $messageSubject,
188                         'body'       => $multipartMessageBody,
189                         'headers'    => $messageHeader,
190                         'parameters' => $sendmail_params,
191                         'sent'       => false,
192                 ];
193
194                 Hook::callAll('emailer_send', $hookdata);
195
196                 if ($hookdata['sent']) {
197                         return true;
198                 }
199
200                 $res = mail(
201                         $hookdata['to'],
202                         $hookdata['subject'],
203                         $hookdata['body'],
204                         $hookdata['headers'],
205                         $hookdata['parameters']
206                 );
207                 $this->logger->debug('header ' . 'To: ' . $email->getToAddress() . '\n' . $messageHeader);
208                 $this->logger->debug('return value ' . (($res) ? 'true' : 'false'));
209                 return $res;
210         }
211 }