Merge branch 'develop' of https://github.com/friendica/friendica into develop
[friendica.git/.git] / src / Util / Emailer.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2024, the Friendica project
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\Capability\IManageConfigValues;
26 use Friendica\Core\Hook;
27 use Friendica\Core\L10n;
28 use Friendica\Core\PConfig\Capability\IManagePersonalConfigValues;
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 IManageConfigValues */
42         private $config;
43         /** @var IManagePersonalConfigValues */
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(IManageConfigValues $config, IManagePersonalConfigValues $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->getHost();
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): bool
130         {
131                 Hook::callAll('emailer_send_prepare', $email);
132
133                 if (empty($email)) {
134                         return true;
135                 }
136
137                 // @see https://github.com/friendica/friendica/issues/9142
138                 $countMessageId = 0;
139                 foreach ($email->getAdditionalMailHeader() as $name => $value) {
140                         if (strtolower($name) == 'message-id') {
141                                 $countMessageId += count($value);
142                         }
143                 }
144                 if ($countMessageId > 1) {
145                         $this->logger->warning('More than one Message-ID found - RFC violation', ['email' => $email]);
146                 }
147
148                 $email_textonly = false;
149                 if (!empty($email->getRecipientUid())) {
150                         $email_textonly = $this->pConfig->get($email->getRecipientUid(), 'system', 'email_textonly');
151                 }
152
153                 $fromName       = Email::encodeHeader(html_entity_decode($email->getFromName(), ENT_QUOTES, 'UTF-8'), 'UTF-8');
154                 $fromAddress    = $email->getFromAddress();
155                 $replyTo        = $email->getReplyTo();
156                 $messageSubject = Email::encodeHeader(html_entity_decode($email->getSubject(), ENT_QUOTES, 'UTF-8'), 'UTF-8');
157
158                 // generate a mime boundary
159                 $mimeBoundary = rand(0, 9) . '-'
160                                 . rand(100000000, 999999999) . '-'
161                                 . rand(100000000, 999999999) . '=:'
162                                 . rand(10000, 99999);
163
164                 $messageHeader = $email->getAdditionalMailHeaderString();
165                 if ($countMessageId === 0) {
166                         $messageHeader .= 'Message-ID: <Friendica-Util-Emailer-' . Strings::getRandomHex() . '@' . $this->baseUrl->getHost() . '>' . "\r\n";
167                 }
168
169                 // generate a multipart/alternative message header
170                 $messageHeader .=
171                         "From: $fromName <{$fromAddress}>\r\n" .
172                         "Reply-To: $fromName <{$replyTo}>\r\n" .
173                         "MIME-Version: 1.0\r\n" .
174                         "Content-Type: multipart/alternative; boundary=\"{$mimeBoundary}\"";
175
176                 // assemble the final multipart message body with the text and html types included
177                 $textBody             = chunk_split(base64_encode($email->getMessage(true)));
178                 $htmlBody             = chunk_split(base64_encode($email->getMessage()));
179                 $multipartMessageBody = "--" . $mimeBoundary . "\n" .                    // plain text section
180                                         "Content-Type: text/plain; charset=UTF-8\n" .
181                                         "Content-Transfer-Encoding: base64\n\n" .
182                                         $textBody . "\n";
183
184                 if (!$email_textonly && !is_null($email->getMessage())) {
185                         $multipartMessageBody .=
186                                 "--" . $mimeBoundary . "\n" .                // text/html section
187                                 "Content-Type: text/html; charset=UTF-8\n" .
188                                 "Content-Transfer-Encoding: base64\n\n" .
189                                 $htmlBody . "\n";
190                 }
191                 $multipartMessageBody .=
192                         "--" . $mimeBoundary . "--\n";                    // message ending
193
194                 if ($this->config->get('system', 'sendmail_params', true)) {
195                         $sendmail_params = '-f ' . $fromAddress;
196                 } else {
197                         $sendmail_params = null;
198                 }
199
200                 // send the message
201                 $hookdata = [
202                         'to'         => $email->getToAddress(),
203                         'subject'    => $messageSubject,
204                         'body'       => $multipartMessageBody,
205                         'headers'    => $messageHeader,
206                         'parameters' => $sendmail_params,
207                         'sent'       => false,
208                 ];
209
210                 Hook::callAll('emailer_send', $hookdata);
211
212                 if ($hookdata['sent']) {
213                         return true;
214                 }
215
216                 $res = $this->mail(
217                         $hookdata['to'],
218                         $hookdata['subject'],
219                         $hookdata['body'],
220                         $hookdata['headers'],
221                         $hookdata['parameters']
222                 );
223
224                 $this->logger->debug('header ' . 'To: ' . $email->getToAddress() . '\n' . $messageHeader);
225                 $this->logger->debug('return value ' . (($res) ? 'true' : 'false'));
226
227                 return $res;
228         }
229
230         /**
231          * Wrapper around the mail() method (mainly used to overwrite for tests)
232          * @see mail()
233          *
234          * @param string $to         Recipient of this mail
235          * @param string $subject    Subject of this mail
236          * @param string $body       Message body of this mail
237          * @param string $headers    Headers of this mail
238          * @param string $parameters Additional (sendmail) parameters of this mail
239          *
240          * @return boolean true if the mail was successfully accepted for delivery, false otherwise.
241          */
242         protected function mail(string $to, string $subject, string $body, string $headers, string $parameters)
243         {
244                 return mail($to, $subject, $body, $headers, $parameters);
245         }
246 }