]> git.mxchange.org Git - friendica.git/blob - src/Model/Mail.php
Simplify sender handle assignment in Model\Mail
[friendica.git] / src / Model / Mail.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\Model;
23
24 use Friendica\Core\Logger;
25 use Friendica\Core\System;
26 use Friendica\Core\Worker;
27 use Friendica\DI;
28 use Friendica\Database\DBA;
29 use Friendica\Model\Notify\Type;
30 use Friendica\Network\Probe;
31 use Friendica\Protocol\Activity;
32 use Friendica\Util\DateTimeFormat;
33 use Friendica\Worker\Delivery;
34
35 /**
36  * Class to handle private messages
37  */
38 class Mail
39 {
40         /**
41          * Insert received private message
42          *
43          * @param array $msg
44          * @return int|boolean Message ID or false on error
45          */
46         public static function insert($msg)
47         {
48                 $user = User::getById($msg['uid']);
49
50                 if (!isset($msg['reply'])) {
51                         $msg['reply'] = DBA::exists('mail', ['parent-uri' => $msg['parent-uri']]);
52                 }
53
54                 if (empty($msg['convid'])) {
55                         $mail = DBA::selectFirst('mail', ['convid'], ["`convid` != 0 AND `parent-uri` = ?", $msg['parent-uri']]);
56                         if (DBA::isResult($mail)) {
57                                 $msg['convid'] = $mail['convid'];
58                         }
59                 }
60
61                 if (empty($msg['guid'])) {
62                         $host = parse_url($msg['from-url'], PHP_URL_HOST);
63                         $msg['guid'] = Item::guidFromUri($msg['uri'], $host);
64                 }
65
66                 $msg['created'] = (!empty($msg['created']) ? DateTimeFormat::utc($msg['created']) : DateTimeFormat::utcNow());
67
68                 DBA::lock('mail');
69
70                 if (DBA::exists('mail', ['uri' => $msg['uri'], 'uid' => $msg['uid']])) {
71                         DBA::unlock();
72                         Logger::info('duplicate message already delivered.');
73                         return false;
74                 }
75
76                 DBA::insert('mail', $msg);
77
78                 $msg['id'] = DBA::lastInsertId();
79
80                 DBA::unlock();
81
82                 if (!empty($msg['convid'])) {
83                         DBA::update('conv', ['updated' => DateTimeFormat::utcNow()], ['id' => $msg['convid']]);
84                 }
85
86                 // send notifications.
87                 $notif_params = [
88                         'type' => Type::MAIL,
89                         'notify_flags' => $user['notify-flags'],
90                         'language' => $user['language'],
91                         'to_name' => $user['username'],
92                         'to_email' => $user['email'],
93                         'uid' => $user['uid'],
94                         'item' => $msg,
95                         'parent' => $msg['id'],
96                         'source_name' => $msg['from-name'],
97                         'source_link' => $msg['from-url'],
98                         'source_photo' => $msg['from-photo'],
99                         'verb' => Activity::POST,
100                         'otype' => 'mail'
101                 ];
102
103                 notification($notif_params);
104
105                 Logger::info('Mail is processed, notification was sent.', ['id' => $msg['id'], 'uri' => $msg['uri']]);
106
107                 return $msg['id'];
108         }
109
110         /**
111          * Send private message
112          *
113          * @param integer $recipient recipient id, default 0
114          * @param string  $body      message body, default empty
115          * @param string  $subject   message subject, default empty
116          * @param string  $replyto   reply to
117          * @return int
118          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
119          */
120         public static function send($recipient = 0, $body = '', $subject = '', $replyto = '')
121         {
122                 $a = DI::app();
123
124                 if (!$recipient) {
125                         return -1;
126                 }
127
128                 if (!strlen($subject)) {
129                         $subject = DI::l10n()->t('[no subject]');
130                 }
131
132                 $me = DBA::selectFirst('contact', [], ['uid' => local_user(), 'self' => true]);
133                 $contact = DBA::selectFirst('contact', [], ['id' => $recipient, 'uid' => local_user()]);
134
135                 if (!(count($me) && (count($contact)))) {
136                         return -2;
137                 }
138
139                 Photo::setPermissionFromBody($body, local_user(), $me['id'],  '<' . $contact['id'] . '>', '', '', '');
140
141                 $guid = System::createUUID();
142                 $uri = Item::newURI(local_user(), $guid);
143
144                 $convid = 0;
145                 $reply = false;
146
147                 // look for any existing conversation structure
148
149                 if (strlen($replyto)) {
150                         $reply = true;
151                         $condition = ["`uid` = ? AND (`uri` = ? OR `parent-uri` = ?)",
152                                 local_user(), $replyto, $replyto];
153                         $mail = DBA::selectFirst('mail', ['convid'], $condition);
154                         if (DBA::isResult($mail)) {
155                                 $convid = $mail['convid'];
156                         }
157                 }
158
159                 $convuri = '';
160                 if (!$convid) {
161                         // create a new conversation
162                         $recip_host = substr($contact['url'], strpos($contact['url'], '://') + 3);
163                         $recip_host = substr($recip_host, 0, strpos($recip_host, '/'));
164
165                         $recip_handle = (($contact['addr']) ? $contact['addr'] : $contact['nick'] . '@' . $recip_host);
166                         $sender_handle = $a->user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3);
167
168                         $conv_guid = System::createUUID();
169                         $convuri = $recip_handle . ':' . $conv_guid;
170
171                         $handles = $recip_handle . ';' . $sender_handle;
172
173                         $fields = ['uid' => local_user(), 'guid' => $conv_guid, 'creator' => $sender_handle,
174                                 'created' => DateTimeFormat::utcNow(), 'updated' => DateTimeFormat::utcNow(),
175                                 'subject' => $subject, 'recips' => $handles];
176                         if (DBA::insert('conv', $fields)) {
177                                 $convid = DBA::lastInsertId();
178                         }
179                 }
180
181                 if (!$convid) {
182                         Logger::log('send message: conversation not found.');
183                         return -4;
184                 }
185
186                 if (!strlen($replyto)) {
187                         $replyto = $convuri;
188                 }
189
190                 $post_id = null;
191                 $success = DBA::insert(
192                         'mail',
193                         [
194                                 'uid' => local_user(),
195                                 'guid' => $guid,
196                                 'convid' => $convid,
197                                 'from-name' => $me['name'],
198                                 'from-photo' => $me['thumb'],
199                                 'from-url' => $me['url'],
200                                 'contact-id' => $recipient,
201                                 'title' => $subject,
202                                 'body' => $body,
203                                 'seen' => 1,
204                                 'reply' => $reply,
205                                 'replied' => 0,
206                                 'uri' => $uri,
207                                 'parent-uri' => $replyto,
208                                 'created' => DateTimeFormat::utcNow()
209                         ]
210                 );
211
212                 if ($success) {
213                         $post_id = DBA::lastInsertId();
214                 }
215
216                 /**
217                  *
218                  * When a photo was uploaded into the message using the (profile wall) ajax
219                  * uploader, The permissions are initially set to disallow anybody but the
220                  * owner from seeing it. This is because the permissions may not yet have been
221                  * set for the post. If it's private, the photo permissions should be set
222                  * appropriately. But we didn't know the final permissions on the post until
223                  * now. So now we'll look for links of uploaded messages that are in the
224                  * post and set them to the same permissions as the post itself.
225                  *
226                  */
227                 $match = null;
228                 if (preg_match_all("/\[img\](.*?)\[\/img\]/", $body, $match)) {
229                         $images = $match[1];
230                         if (count($images)) {
231                                 foreach ($images as $image) {
232                                         $image_rid = Photo::ridFromURI($image);
233                                         if (!empty($image_rid)) {
234                                                 Photo::update(['allow-cid' => '<' . $recipient . '>'], ['resource-id' => $image_rid, 'album' => 'Wall Photos', 'uid' => local_user()]);
235                                         }
236                                 }
237                         }
238                 }
239
240                 if ($post_id) {
241                         Worker::add(PRIORITY_HIGH, "Notifier", Delivery::MAIL, $post_id);
242                         return intval($post_id);
243                 } else {
244                         return -3;
245                 }
246         }
247
248         /**
249          * @param array  $recipient recipient, default empty
250          * @param string $body      message body, default empty
251          * @param string $subject   message subject, default empty
252          * @param string $replyto   reply to, default empty
253          * @return int
254          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
255          * @throws \ImagickException
256          */
257         public static function sendWall(array $recipient = [], $body = '', $subject = '', $replyto = '')
258         {
259                 if (!$recipient) {
260                         return -1;
261                 }
262
263                 if (!strlen($subject)) {
264                         $subject = DI::l10n()->t('[no subject]');
265                 }
266
267                 $guid = System::createUUID();
268                 $uri = Item::newURI(local_user(), $guid);
269
270                 $me = Probe::uri($replyto);
271                 if (!$me['name']) {
272                         return -2;
273                 }
274
275                 $conv_guid = System::createUUID();
276
277                 $recip_handle = $recipient['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3);
278
279                 $sender_handle = $me['addr'];
280
281                 $handles = $recip_handle . ';' . $sender_handle;
282
283                 $convid = null;
284                 $fields = ['uid' => $recipient['uid'], 'guid' => $conv_guid, 'creator' => $sender_handle,
285                         'created' => DateTimeFormat::utcNow(), 'updated' => DateTimeFormat::utcNow(),
286                         'subject' => $subject, 'recips' => $handles];
287                 if (DBA::insert('conv', $fields)) {
288                         $convid = DBA::lastInsertId();
289                 }
290
291                 if (!$convid) {
292                         Logger::log('send message: conversation not found.');
293                         return -4;
294                 }
295
296                 DBA::insert(
297                         'mail',
298                         [
299                                 'uid' => $recipient['uid'],
300                                 'guid' => $guid,
301                                 'convid' => $convid,
302                                 'from-name' => $me['name'],
303                                 'from-photo' => $me['photo'],
304                                 'from-url' => $me['url'],
305                                 'contact-id' => 0,
306                                 'title' => $subject,
307                                 'body' => $body,
308                                 'seen' => 0,
309                                 'reply' => 0,
310                                 'replied' => 0,
311                                 'uri' => $uri,
312                                 'parent-uri' => $me['url'],
313                                 'created' => DateTimeFormat::utcNow(),
314                                 'unknown' => 1
315                         ]
316                 );
317
318                 return 0;
319         }
320 }