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