"uri-id" instead of "uri" or "id"
[friendica.git/.git] / mod / message.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2020, Friendica
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 use Friendica\App;
23 use Friendica\Content\Nav;
24 use Friendica\Content\Pager;
25 use Friendica\Content\Text\BBCode;
26 use Friendica\Core\ACL;
27 use Friendica\Core\Renderer;
28 use Friendica\Database\DBA;
29 use Friendica\DI;
30 use Friendica\Model\Contact;
31 use Friendica\Model\Mail;
32 use Friendica\Module\Security\Login;
33 use Friendica\Util\DateTimeFormat;
34 use Friendica\Util\Strings;
35 use Friendica\Util\Temporal;
36
37 function message_init(App $a)
38 {
39         $tabs = '';
40
41         if ($a->argc > 1 && is_numeric($a->argv[1])) {
42                 $tabs = render_messages(get_messages(local_user(), 0, 5), 'mail_list.tpl');
43         }
44
45         $new = [
46                 'label' => DI::l10n()->t('New Message'),
47                 'url' => 'message/new',
48                 'sel' => $a->argc > 1 && $a->argv[1] == 'new',
49                 'accesskey' => 'm',
50         ];
51
52         $tpl = Renderer::getMarkupTemplate('message_side.tpl');
53         DI::page()['aside'] = Renderer::replaceMacros($tpl, [
54                 '$tabs' => $tabs,
55                 '$new' => $new,
56         ]);
57         $base = DI::baseUrl();
58
59         $head_tpl = Renderer::getMarkupTemplate('message-head.tpl');
60         DI::page()['htmlhead'] .= Renderer::replaceMacros($head_tpl, [
61                 '$baseurl' => DI::baseUrl()->get(true),
62                 '$base' => $base
63         ]);
64 }
65
66 function message_post(App $a)
67 {
68         if (!local_user()) {
69                 notice(DI::l10n()->t('Permission denied.'));
70                 return;
71         }
72
73         $replyto   = !empty($_REQUEST['replyto'])   ? Strings::escapeTags(trim($_REQUEST['replyto'])) : '';
74         $subject   = !empty($_REQUEST['subject'])   ? Strings::escapeTags(trim($_REQUEST['subject'])) : '';
75         $body      = !empty($_REQUEST['body'])      ? Strings::escapeHtml(trim($_REQUEST['body']))    : '';
76         $recipient = !empty($_REQUEST['recipient']) ? intval($_REQUEST['recipient'])                  : 0;
77
78         $ret = Mail::send($recipient, $body, $subject, $replyto);
79         $norecip = false;
80
81         switch ($ret) {
82                 case -1:
83                         notice(DI::l10n()->t('No recipient selected.'));
84                         $norecip = true;
85                         break;
86                 case -2:
87                         notice(DI::l10n()->t('Unable to locate contact information.'));
88                         break;
89                 case -3:
90                         notice(DI::l10n()->t('Message could not be sent.'));
91                         break;
92                 case -4:
93                         notice(DI::l10n()->t('Message collection failure.'));
94                         break;
95         }
96
97         // fake it to go back to the input form if no recipient listed
98         if ($norecip) {
99                 $a->argc = 2;
100                 $a->argv[1] = 'new';
101         } else {
102                 DI::baseUrl()->redirect(DI::args()->getCommand() . '/' . $ret);
103         }
104 }
105
106 function message_content(App $a)
107 {
108         $o = '';
109         Nav::setSelected('messages');
110
111         if (!local_user()) {
112                 notice(DI::l10n()->t('Permission denied.'));
113                 return Login::form();
114         }
115
116         $myprofile = DI::baseUrl() . '/profile/' . $a->user['nickname'];
117
118         $tpl = Renderer::getMarkupTemplate('mail_head.tpl');
119         if ($a->argc > 1 && $a->argv[1] == 'new') {
120                 $button = [
121                         'label' => DI::l10n()->t('Discard'),
122                         'url' => '/message',
123                         'sel' => 'close',
124                 ];
125         } else {
126                 $button = [
127                         'label' => DI::l10n()->t('New Message'),
128                         'url' => '/message/new',
129                         'sel' => 'new',
130                         'accesskey' => 'm',
131                 ];
132         }
133         $header = Renderer::replaceMacros($tpl, [
134                 '$messages' => DI::l10n()->t('Messages'),
135                 '$button' => $button,
136         ]);
137
138         if (($a->argc == 3) && ($a->argv[1] === 'drop' || $a->argv[1] === 'dropconv')) {
139                 if (!intval($a->argv[2])) {
140                         return;
141                 }
142
143                 $cmd = $a->argv[1];
144                 if ($cmd === 'drop') {
145                         $message = DBA::selectFirst('mail', ['convid'], ['id' => $a->argv[2], 'uid' => local_user()]);
146                         if(!DBA::isResult($message)){
147                                 notice(DI::l10n()->t('Conversation not found.'));
148                                 DI::baseUrl()->redirect('message');
149                         }
150
151                         if (!DBA::delete('mail', ['id' => $a->argv[2], 'uid' => local_user()])) {
152                                 notice(DI::l10n()->t('Message was not deleted.'));
153                         }
154
155                         $conversation = DBA::selectFirst('mail', ['id'], ['convid' => $message['convid'], 'uid' => local_user()]);
156                         if(!DBA::isResult($conversation)){
157                                 DI::baseUrl()->redirect('message');
158                         }
159
160                         DI::baseUrl()->redirect('message/' . $conversation['id'] );
161                 } else {
162                         $r = q("SELECT `parent-uri`,`convid` FROM `mail` WHERE `id` = %d AND `uid` = %d LIMIT 1",
163                                 intval($a->argv[2]),
164                                 intval(local_user())
165                         );
166                         if (DBA::isResult($r)) {
167                                 $parent = $r[0]['parent-uri'];
168
169                                 if (!DBA::delete('mail', ['parent-uri' => $parent, 'uid' => local_user()])) {
170                                         notice(DI::l10n()->t('Conversation was not removed.'));
171                                 }
172                         }
173                         DI::baseUrl()->redirect('message');
174                 }
175         }
176
177         if (($a->argc > 1) && ($a->argv[1] === 'new')) {
178                 $o .= $header;
179
180                 $tpl = Renderer::getMarkupTemplate('msg-header.tpl');
181                 DI::page()['htmlhead'] .= Renderer::replaceMacros($tpl, [
182                         '$baseurl' => DI::baseUrl()->get(true),
183                         '$nickname' => $a->user['nickname'],
184                         '$linkurl' => DI::l10n()->t('Please enter a link URL:')
185                 ]);
186
187                 $recipientId = $a->argv[2] ?? null;
188
189                 $select = ACL::getMessageContactSelectHTML($recipientId);
190
191                 $tpl = Renderer::getMarkupTemplate('prv_message.tpl');
192                 $o .= Renderer::replaceMacros($tpl, [
193                         '$header'     => DI::l10n()->t('Send Private Message'),
194                         '$to'         => DI::l10n()->t('To:'),
195                         '$subject'    => DI::l10n()->t('Subject:'),
196                         '$subjtxt'    => $_REQUEST['subject'] ?? '',
197                         '$text'       => $_REQUEST['body'] ?? '',
198                         '$readonly'   => '',
199                         '$yourmessage'=> DI::l10n()->t('Your message:'),
200                         '$select'     => $select,
201                         '$parent'     => '',
202                         '$upload'     => DI::l10n()->t('Upload photo'),
203                         '$insert'     => DI::l10n()->t('Insert web link'),
204                         '$wait'       => DI::l10n()->t('Please wait'),
205                         '$submit'     => DI::l10n()->t('Submit')
206                 ]);
207                 return $o;
208         }
209
210
211         $_SESSION['return_path'] = DI::args()->getQueryString();
212
213         if ($a->argc == 1) {
214
215                 // List messages
216
217                 $o .= $header;
218
219                 $total = 0;
220                 $r = q("SELECT count(*) AS `total`, ANY_VALUE(`created`) AS `created` FROM `mail`
221                         WHERE `mail`.`uid` = %d GROUP BY `parent-uri` ORDER BY `created` DESC",
222                         intval(local_user())
223                 );
224                 if (DBA::isResult($r)) {
225                         $total = $r[0]['total'];
226                 }
227
228                 $pager = new Pager(DI::l10n(), DI::args()->getQueryString());
229
230                 $r = get_messages(local_user(), $pager->getStart(), $pager->getItemsPerPage());
231
232                 if (!DBA::isResult($r)) {
233                         notice(DI::l10n()->t('No messages.'));
234                         return $o;
235                 }
236
237                 $o .= render_messages($r, 'mail_list.tpl');
238
239                 $o .= $pager->renderFull($total);
240
241                 return $o;
242         }
243
244         if (($a->argc > 1) && (intval($a->argv[1]))) {
245
246                 $o .= $header;
247
248                 $message = DBA::fetchFirst("
249                         SELECT `mail`.*, `contact`.`name`, `contact`.`url`, `contact`.`thumb`
250                         FROM `mail`
251                         LEFT JOIN `contact` ON `mail`.`contact-id` = `contact`.`id`
252                         WHERE `mail`.`uid` = ? AND `mail`.`id` = ?
253                         LIMIT 1",
254                         local_user(),
255                         $a->argv[1]
256                 );
257                 if (DBA::isResult($message)) {
258                         $contact_id = $message['contact-id'];
259
260                         $params = [
261                                 local_user(),
262                                 $message['parent-uri']
263                         ];
264
265                         if ($message['convid']) {
266                                 $sql_extra = "AND (`mail`.`parent-uri` = ? OR `mail`.`convid` = ?)";
267                                 $params[] = $message['convid'];
268                         } else {
269                                 $sql_extra = "AND `mail`.`parent-uri` = ?";
270                         }
271                         $messages_stmt = DBA::p("
272                                 SELECT `mail`.*, `contact`.`name`, `contact`.`url`, `contact`.`thumb`
273                                 FROM `mail`
274                                 LEFT JOIN `contact` ON `mail`.`contact-id` = `contact`.`id`
275                                 WHERE `mail`.`uid` = ?
276                                 $sql_extra
277                                 ORDER BY `mail`.`created` ASC",
278                                 ...$params
279                         );
280
281                         $messages = DBA::toArray($messages_stmt);
282
283                         DBA::update('mail', ['seen' => 1], ['parent-uri' => $message['parent-uri'], 'uid' => local_user()]);
284                 } else {
285                         $messages = false;
286                 }
287
288                 if (!DBA::isResult($messages)) {
289                         notice(DI::l10n()->t('Message not available.'));
290                         return $o;
291                 }
292
293                 $tpl = Renderer::getMarkupTemplate('msg-header.tpl');
294                 DI::page()['htmlhead'] .= Renderer::replaceMacros($tpl, [
295                         '$baseurl' => DI::baseUrl()->get(true),
296                         '$nickname' => $a->user['nickname'],
297                         '$linkurl' => DI::l10n()->t('Please enter a link URL:')
298                 ]);
299
300                 $mails = [];
301                 $seen = 0;
302                 $unknown = false;
303
304                 foreach ($messages as $message) {
305                         if ($message['unknown']) {
306                                 $unknown = true;
307                         }
308
309                         if ($message['from-url'] == $myprofile) {
310                                 $from_url = $myprofile;
311                                 $sparkle = '';
312                         } else {
313                                 $from_url = Contact::magicLink($message['from-url']);
314                                 $sparkle = ' sparkle';
315                         }
316
317                         $extracted = item_extract_images($message['body']);
318                         if ($extracted['images']) {
319                                 $message['body'] = item_redir_and_replace_images($extracted['body'], $extracted['images'], $message['contact-id']);
320                         }
321
322                         $from_name_e = $message['from-name'];
323                         $subject_e = $message['title'];
324                         $body_e = BBCode::convert($message['body']);
325                         $to_name_e = $message['name'];
326
327                         $contact = Contact::getByURL($message['from-url'], false, ['thumb', 'addr', 'id', 'avatar']);
328                         $from_photo = Contact::getThumb($contact, $message['from-photo']);
329
330                         $mails[] = [
331                                 'id' => $message['id'],
332                                 'from_name' => $from_name_e,
333                                 'from_url' => $from_url,
334                                 'from_addr' => $contact['addr'] ?? $from_url,
335                                 'sparkle' => $sparkle,
336                                 'from_photo' => $from_photo,
337                                 'subject' => $subject_e,
338                                 'body' => $body_e,
339                                 'delete' => DI::l10n()->t('Delete message'),
340                                 'to_name' => $to_name_e,
341                                 'date' => DateTimeFormat::local($message['created'], DI::l10n()->t('D, d M Y - g:i A')),
342                                 'ago' => Temporal::getRelativeDate($message['created']),
343                         ];
344
345                         $seen = $message['seen'];
346                 }
347
348                 $select = $message['name'] . '<input type="hidden" name="recipient" value="' . $contact_id . '" />';
349                 $parent = '<input type="hidden" name="replyto" value="' . $message['parent-uri'] . '" />';
350
351                 $tpl = Renderer::getMarkupTemplate('mail_display.tpl');
352                 $o = Renderer::replaceMacros($tpl, [
353                         '$thread_id' => $a->argv[1],
354                         '$thread_subject' => $message['title'],
355                         '$thread_seen' => $seen,
356                         '$delete' => DI::l10n()->t('Delete conversation'),
357                         '$canreply' => (($unknown) ? false : '1'),
358                         '$unknown_text' => DI::l10n()->t("No secure communications available. You <strong>may</strong> be able to respond from the sender's profile page."),
359                         '$mails' => $mails,
360
361                         // reply
362                         '$header' => DI::l10n()->t('Send Reply'),
363                         '$to' => DI::l10n()->t('To:'),
364                         '$subject' => DI::l10n()->t('Subject:'),
365                         '$subjtxt' => $message['title'],
366                         '$readonly' => ' readonly="readonly" style="background: #BBBBBB;" ',
367                         '$yourmessage' => DI::l10n()->t('Your message:'),
368                         '$text' => '',
369                         '$select' => $select,
370                         '$parent' => $parent,
371                         '$upload' => DI::l10n()->t('Upload photo'),
372                         '$insert' => DI::l10n()->t('Insert web link'),
373                         '$submit' => DI::l10n()->t('Submit'),
374                         '$wait' => DI::l10n()->t('Please wait')
375                 ]);
376
377                 return $o;
378         }
379 }
380
381 /**
382  * @param int $uid
383  * @param int $start
384  * @param int $limit
385  * @return array
386  */
387 function get_messages(int $uid, int $start, int $limit)
388 {
389         return DBA::toArray(DBA::p('SELECT
390                         m.`id`,
391                         m.`uid`,
392                         m.`guid`,
393                         m.`from-name`,
394                         m.`from-photo`,
395                         m.`from-url`,
396                         m.`contact-id`,
397                         m.`convid`,
398                         m.`title`,
399                         m.`body`,
400                         m.`seen`,
401                         m.`reply`,
402                         m.`replied`,
403                         m.`unknown`,
404                         m.`uri`,
405                         m.`parent-uri`,
406                         m.`created`,
407                         c.`name`,
408                         c.`url`,
409                         c.`thumb`,
410                         c.`network`,
411                 m2.`count`,
412                 m2.`mailcreated`,
413                 m2.`mailseen`
414         FROM `mail` m
415         JOIN (
416                 SELECT
417                         `parent-uri`,
418                     MIN(`id`)      AS `id`,
419                     COUNT(*)       AS `count`,
420                     MAX(`created`) AS `mailcreated`,
421                     MIN(`seen`)    AS `mailseen`
422                 FROM `mail`
423                 WHERE `uid` = ?
424                 GROUP BY `parent-uri`
425         ) m2 ON m.`parent-uri` = m2.`parent-uri` AND m.`id` = m2.`id`
426                 LEFT JOIN `contact` c ON m.`contact-id` = c.`id`
427                 WHERE m.`uid` = ?
428                 ORDER BY m2.`mailcreated` DESC
429                 LIMIT ?, ?'
430                 , $uid, $uid, $start, $limit));
431 }
432
433 function render_messages(array $msg, $t)
434 {
435         $a = DI::app();
436
437         $tpl = Renderer::getMarkupTemplate($t);
438         $rslt = '';
439
440         $myprofile = DI::baseUrl() . '/profile/' . $a->user['nickname'];
441
442         foreach ($msg as $rr) {
443                 if ($rr['unknown']) {
444                         $participants = DI::l10n()->t("Unknown sender - %s", $rr['from-name']);
445                 } elseif (Strings::compareLink($rr['from-url'], $myprofile)) {
446                         $participants = DI::l10n()->t("You and %s", $rr['name']);
447                 } else {
448                         $participants = DI::l10n()->t("%s and You", $rr['from-name']);
449                 }
450
451                 $body_e = $rr['body'];
452                 $to_name_e = $rr['name'];
453
454                 $contact = Contact::getByURL($rr['url'], false, ['thumb', 'addr', 'id', 'avatar']);
455                 $from_photo = Contact::getThumb($contact, $rr['thumb'] ?: $rr['from-photo']);
456
457                 $rslt .= Renderer::replaceMacros($tpl, [
458                         '$id' => $rr['id'],
459                         '$from_name' => $participants,
460                         '$from_url' => Contact::magicLink($rr['url']),
461                         '$from_addr' => $contact['addr'] ?? '',
462                         '$sparkle' => ' sparkle',
463                         '$from_photo' => $from_photo,
464                         '$subject' => $rr['title'],
465                         '$delete' => DI::l10n()->t('Delete conversation'),
466                         '$body' => $body_e,
467                         '$to_name' => $to_name_e,
468                         '$date' => DateTimeFormat::local($rr['mailcreated'], DI::l10n()->t('D, d M Y - g:i A')),
469                         '$ago' => Temporal::getRelativeDate($rr['mailcreated']),
470                         '$seen' => $rr['mailseen'],
471                         '$count' => DI::l10n()->tt('%d message', '%d messages', $rr['count']),
472                 ]);
473         }
474
475         return $rslt;
476 }