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