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