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