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