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