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