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