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