Merge pull request #8261 from MrPetovan/task/8251-use-about-for-pdesc
[friendica.git/.git] / src / Util / EMailer / MailBuilder.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\EMailer;
23
24 use Exception;
25 use Friendica\App\BaseURL;
26 use Friendica\Core\Config\IConfig;
27 use Friendica\Core\L10n;
28 use Friendica\Core\Renderer;
29 use Friendica\Model\User;
30 use Friendica\Network\HTTPException\InternalServerErrorException;
31 use Friendica\Object\Email;
32 use Friendica\Object\EMail\IEmail;
33 use Psr\Log\LoggerInterface;
34
35 /**
36  * A base class for building new emails
37  */
38 abstract class MailBuilder
39 {
40         /** @var string The default email banner in case nothing else is defined */
41         const DEFAULT_EMAIL_BANNER = 'images/friendica-32.png';
42
43         /** @var L10n */
44         protected $l10n;
45         /** @var IConfig */
46         protected $config;
47         /** @var BaseURL */
48         protected $baseUrl;
49         /** @var LoggerInterface */
50         protected $logger;
51
52         /** @var string */
53         protected $headers;
54
55         /** @var string */
56         protected $senderName = null;
57         /** @var string */
58         protected $senderAddress = null;
59         /** @var string */
60         protected $senderNoReply = null;
61
62         /** @var string */
63         protected $recipientAddress = null;
64         /** @var int */
65         protected $recipientUid = null;
66
67         public function __construct(L10n $l10n, BaseURL $baseUrl, IConfig $config, LoggerInterface $logger)
68         {
69                 $this->l10n    = $l10n;
70                 $this->baseUrl = $baseUrl;
71                 $this->config  = $config;
72                 $this->logger  = $logger;
73
74                 $hostname = $baseUrl->getHostname();
75                 if (strpos($hostname, ':')) {
76                         $hostname = substr($hostname, 0, strpos($hostname, ':'));
77                 }
78
79                 $this->headers = "";
80                 $this->headers .= "Precedence: list\n";
81                 $this->headers .= "X-Friendica-Host: " . $hostname . "\n";
82                 $this->headers .= "X-Friendica-Platform: " . FRIENDICA_PLATFORM . "\n";
83                 $this->headers .= "X-Friendica-Version: " . FRIENDICA_VERSION . "\n";
84                 $this->headers .= "List-ID: <notification." . $hostname . ">\n";
85                 $this->headers .= "List-Archive: <" . $baseUrl->get() . "/notifications/system>\n";
86         }
87
88         /**
89          * Gets the subject of the concrete builder, which inherits this base class
90          *
91          * @return string
92          */
93         abstract protected function getSubject();
94
95         /**
96          * Gets the HTML version of the body of the concrete builder, which inherits this base class
97          *
98          * @return string
99          */
100         abstract protected function getHtmlMessage();
101
102         /**
103          * Gets the Plaintext version of the body of the concrete builder, which inherits this base class
104          *
105          * @return string
106          */
107         abstract protected function getPlaintextMessage();
108
109         /**
110          * Adds the User ID to the email in case the mail sending needs additional properties of this user
111          *
112          * @param array $user The user entity/array, for which the email should be sent
113          *
114          * @return static
115          * @todo Once the user array is replaced with a user entity, replace this array parameter as well
116          */
117         public function forUser(array $user)
118         {
119                 $this->recipientUid = $user['uid'] ?? 0;
120                 try {
121                         $this->l10n = $user['language'] ? $this->l10n->withLang($user['language']) : $this->l10n;
122                 } catch (Exception $e) {
123                         $this->logger->warning('cannot use language.', ['user' => $user, 'exception' => $e]);
124                 }
125
126                 return $this;
127         }
128
129         /**
130          * Adds the sender to the email (if not called/set, the sender will get loaded with the help of the user id)
131          *
132          * @param string      $name    The name of the sender
133          * @param string      $address The (email) address of the sender
134          * @param string|null $noReply Optional "no-reply" (email) address (if not set, it's the same as the address)
135          *
136          * @return static
137          */
138         public function withSender(string $name, string $address, string $noReply = null)
139         {
140                 $this->senderName    = $name;
141                 $this->senderAddress = $address;
142                 $this->senderNoReply = $noReply ?? $this->senderNoReply;
143
144                 return $this;
145         }
146
147         /**
148          * Adds a recipient to the email
149          *
150          * @param string $address The (email) address of the recipient
151          *
152          * @return static
153          */
154         public function withRecipient(string $address)
155         {
156                 $this->recipientAddress = $address;
157
158                 return $this;
159         }
160
161         /**
162          * Adds new headers to the default headers
163          *
164          * @param string $headers New headers
165          *
166          * @return static
167          */
168         public function addHeaders(string $headers)
169         {
170                 $this->headers .= $headers;
171
172                 return $this;
173         }
174
175         /**
176          * Build a email based on the given attributes
177          *
178          * @param bool $raw True, if the email shouldn't get extended by the default email-template
179          *
180          * @return IEmail A new generated email
181          *
182          * @throws InternalServerErrorException
183          * @throws Exception
184          */
185         public function build(bool $raw = false)
186         {
187                 if ((empty($this->recipientAddress)) &&
188                     !empty($this->recipientUid)) {
189                         $user = User::getById($this->recipientUid, ['email']);
190
191                         if (!empty($user['email'])) {
192                                 $this->recipientAddress = $user['email'];
193                         }
194                 }
195
196                 if (empty($this->recipientAddress)) {
197                         throw new InternalServerErrorException('Recipient address is missing.');
198                 }
199
200                 if (empty($this->senderAddress) || empty($this->senderName)) {
201                         throw new InternalServerErrorException('Sender address or name is missing.');
202                 }
203
204                 $this->senderNoReply = $this->senderNoReply ?? $this->senderAddress;
205
206                 $msgHtml = $this->getHtmlMessage() ?? '';
207
208                 if (!$raw) {
209                         // load the template for private message notifications
210                         $tpl     = Renderer::getMarkupTemplate('email/html.tpl');
211                         $msgHtml = Renderer::replaceMacros($tpl, [
212                                 '$title'       => $this->l10n->t('Friendica Notification'),
213                                 '$product'     => FRIENDICA_PLATFORM,
214                                 '$htmlversion' => $msgHtml,
215                                 '$sitename'    => $this->config->get('config', 'sitename'),
216                                 '$banner'      => $this->config->get('system', 'email_banner',
217                                         $this->baseUrl->get(true) . DIRECTORY_SEPARATOR . self::DEFAULT_EMAIL_BANNER),
218                         ]);
219                 }
220
221                 return new Email(
222                         $this->senderName,
223                         $this->senderAddress,
224                         $this->senderNoReply,
225                         $this->recipientAddress,
226                         $this->getSubject() ?? '',
227                         $msgHtml,
228                         $this->getPlaintextMessage() ?? '',
229                         $this->headers,
230                         $this->recipientUid ?? null);
231         }
232 }