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