]> git.mxchange.org Git - friendica.git/blob - mod/message.php
AP Improvements for forums
[friendica.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['messageto']) ? intval($_REQUEST['messageto'])                  : 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                 // Check if we should do HTML-based delete confirmation
145                 if (!empty($_REQUEST['confirm'])) {
146                         // <form> can't take arguments in its "action" parameter
147                         // so add any arguments as hidden inputs
148                         $query = explode_querystring(DI::args()->getQueryString());
149                         $inputs = [];
150                         foreach ($query['args'] as $arg) {
151                                 if (strpos($arg, 'confirm=') === false) {
152                                         $arg_parts = explode('=', $arg);
153                                         $inputs[] = ['name' => $arg_parts[0], 'value' => $arg_parts[1]];
154                                 }
155                         }
156
157                         //DI::page()['aside'] = '';
158                         return Renderer::replaceMacros(Renderer::getMarkupTemplate('confirm.tpl'), [
159                                 '$method' => 'get',
160                                 '$message' => DI::l10n()->t('Do you really want to delete this message?'),
161                                 '$extra_inputs' => $inputs,
162                                 '$confirm' => DI::l10n()->t('Yes'),
163                                 '$confirm_url' => $query['base'],
164                                 '$confirm_name' => 'confirmed',
165                                 '$cancel' => DI::l10n()->t('Cancel'),
166                         ]);
167                 }
168
169                 // Now check how the user responded to the confirmation query
170                 if (!empty($_REQUEST['canceled'])) {
171                         DI::baseUrl()->redirect('message');
172                 }
173
174                 $cmd = $a->argv[1];
175                 if ($cmd === 'drop') {
176                         $message = DBA::selectFirst('mail', ['convid'], ['id' => $a->argv[2], 'uid' => local_user()]);
177                         if(!DBA::isResult($message)){
178                                 notice(DI::l10n()->t('Conversation not found.'));
179                                 DI::baseUrl()->redirect('message');
180                         }
181
182                         if (!DBA::delete('mail', ['id' => $a->argv[2], 'uid' => local_user()])) {
183                                 notice(DI::l10n()->t('Message was not deleted.'));
184                         }
185
186                         $conversation = DBA::selectFirst('mail', ['id'], ['convid' => $message['convid'], 'uid' => local_user()]);
187                         if(!DBA::isResult($conversation)){
188                                 DI::baseUrl()->redirect('message');
189                         }
190
191                         DI::baseUrl()->redirect('message/' . $conversation['id'] );
192                 } else {
193                         $r = q("SELECT `parent-uri`,`convid` FROM `mail` WHERE `id` = %d AND `uid` = %d LIMIT 1",
194                                 intval($a->argv[2]),
195                                 intval(local_user())
196                         );
197                         if (DBA::isResult($r)) {
198                                 $parent = $r[0]['parent-uri'];
199
200                                 if (!DBA::delete('mail', ['parent-uri' => $parent, 'uid' => local_user()])) {
201                                         notice(DI::l10n()->t('Conversation was not removed.'));
202                                 }
203                         }
204                         DI::baseUrl()->redirect('message');
205                 }
206         }
207
208         if (($a->argc > 1) && ($a->argv[1] === 'new')) {
209                 $o .= $header;
210
211                 $tpl = Renderer::getMarkupTemplate('msg-header.tpl');
212                 DI::page()['htmlhead'] .= Renderer::replaceMacros($tpl, [
213                         '$baseurl' => DI::baseUrl()->get(true),
214                         '$nickname' => $a->user['nickname'],
215                         '$linkurl' => DI::l10n()->t('Please enter a link URL:')
216                 ]);
217
218                 $preselect = isset($a->argv[2]) ? [$a->argv[2]] : [];
219
220                 $prename = $preurl = $preid = '';
221
222                 if ($preselect) {
223                         $r = q("SELECT `name`, `url`, `id` FROM `contact` WHERE `uid` = %d AND `id` = %d LIMIT 1",
224                                 intval(local_user()),
225                                 intval($a->argv[2])
226                         );
227                         if (!DBA::isResult($r)) {
228                                 $r = q("SELECT `name`, `url`, `id` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' LIMIT 1",
229                                         intval(local_user()),
230                                         DBA::escape(Strings::normaliseLink(base64_decode($a->argv[2])))
231                                 );
232                         }
233
234                         if (!DBA::isResult($r)) {
235                                 $r = q("SELECT `name`, `url`, `id` FROM `contact` WHERE `uid` = %d AND `addr` = '%s' LIMIT 1",
236                                         intval(local_user()),
237                                         DBA::escape(base64_decode($a->argv[2]))
238                                 );
239                         }
240
241                         if (DBA::isResult($r)) {
242                                 $prename = $r[0]['name'];
243                                 $preid = $r[0]['id'];
244                                 $preselect = [$preid];
245                         } else {
246                                 $preselect = [];
247                         }
248                 }
249
250                 $prefill = $preselect ? $prename : '';
251
252                 // the ugly select box
253                 $select = ACL::getMessageContactSelectHTML('messageto', 'message-to-select', $preselect, 4, 10);
254
255                 $tpl = Renderer::getMarkupTemplate('prv_message.tpl');
256                 $o .= Renderer::replaceMacros($tpl, [
257                         '$header'     => DI::l10n()->t('Send Private Message'),
258                         '$to'         => DI::l10n()->t('To:'),
259                         '$showinputs' => 'true',
260                         '$prefill'    => $prefill,
261                         '$preid'      => $preid,
262                         '$subject'    => DI::l10n()->t('Subject:'),
263                         '$subjtxt'    => $_REQUEST['subject'] ?? '',
264                         '$text'       => $_REQUEST['body'] ?? '',
265                         '$readonly'   => '',
266                         '$yourmessage'=> DI::l10n()->t('Your message:'),
267                         '$select'     => $select,
268                         '$parent'     => '',
269                         '$upload'     => DI::l10n()->t('Upload photo'),
270                         '$insert'     => DI::l10n()->t('Insert web link'),
271                         '$wait'       => DI::l10n()->t('Please wait'),
272                         '$submit'     => DI::l10n()->t('Submit')
273                 ]);
274                 return $o;
275         }
276
277
278         $_SESSION['return_path'] = DI::args()->getQueryString();
279
280         if ($a->argc == 1) {
281
282                 // List messages
283
284                 $o .= $header;
285
286                 $total = 0;
287                 $r = q("SELECT count(*) AS `total`, ANY_VALUE(`created`) AS `created` FROM `mail`
288                         WHERE `mail`.`uid` = %d GROUP BY `parent-uri` ORDER BY `created` DESC",
289                         intval(local_user())
290                 );
291                 if (DBA::isResult($r)) {
292                         $total = $r[0]['total'];
293                 }
294
295                 $pager = new Pager(DI::l10n(), DI::args()->getQueryString());
296
297                 $r = get_messages(local_user(), $pager->getStart(), $pager->getItemsPerPage());
298
299                 if (!DBA::isResult($r)) {
300                         notice(DI::l10n()->t('No messages.'));
301                         return $o;
302                 }
303
304                 $o .= render_messages($r, 'mail_list.tpl');
305
306                 $o .= $pager->renderFull($total);
307
308                 return $o;
309         }
310
311         if (($a->argc > 1) && (intval($a->argv[1]))) {
312
313                 $o .= $header;
314
315                 $message = DBA::fetchFirst("
316                         SELECT `mail`.*, `contact`.`name`, `contact`.`url`, `contact`.`thumb`
317                         FROM `mail`
318                         LEFT JOIN `contact` ON `mail`.`contact-id` = `contact`.`id`
319                         WHERE `mail`.`uid` = ? AND `mail`.`id` = ?
320                         LIMIT 1",
321                         local_user(),
322                         $a->argv[1]
323                 );
324                 if (DBA::isResult($message)) {
325                         $contact_id = $message['contact-id'];
326
327                         $params = [
328                                 local_user(),
329                                 $message['parent-uri']
330                         ];
331
332                         if ($message['convid']) {
333                                 $sql_extra = "AND (`mail`.`parent-uri` = ? OR `mail`.`convid` = ?)";
334                                 $params[] = $message['convid'];
335                         } else {
336                                 $sql_extra = "AND `mail`.`parent-uri` = ?";
337                         }
338                         $messages_stmt = DBA::p("
339                                 SELECT `mail`.*, `contact`.`name`, `contact`.`url`, `contact`.`thumb`
340                                 FROM `mail`
341                                 LEFT JOIN `contact` ON `mail`.`contact-id` = `contact`.`id`
342                                 WHERE `mail`.`uid` = ?
343                                 $sql_extra
344                                 ORDER BY `mail`.`created` ASC",
345                                 ...$params
346                         );
347
348                         $messages = DBA::toArray($messages_stmt);
349
350                         DBA::update('mail', ['seen' => 1], ['parent-uri' => $message['parent-uri'], 'uid' => local_user()]);
351                         DBA::update('notify', ['seen' => 1], ['type' => Type::MAIL, 'parent' => $message['id'], 'uid' => local_user()]);
352                 } else {
353                         $messages = false;
354                 }
355
356                 if (!DBA::isResult($messages)) {
357                         notice(DI::l10n()->t('Message not available.'));
358                         return $o;
359                 }
360
361                 $tpl = Renderer::getMarkupTemplate('msg-header.tpl');
362                 DI::page()['htmlhead'] .= Renderer::replaceMacros($tpl, [
363                         '$baseurl' => DI::baseUrl()->get(true),
364                         '$nickname' => $a->user['nickname'],
365                         '$linkurl' => DI::l10n()->t('Please enter a link URL:')
366                 ]);
367
368                 $mails = [];
369                 $seen = 0;
370                 $unknown = false;
371
372                 foreach ($messages as $message) {
373                         if ($message['unknown']) {
374                                 $unknown = true;
375                         }
376
377                         if ($message['from-url'] == $myprofile) {
378                                 $from_url = $myprofile;
379                                 $sparkle = '';
380                         } else {
381                                 $from_url = Contact::magicLink($message['from-url']);
382                                 $sparkle = ' sparkle';
383                         }
384
385                         $extracted = item_extract_images($message['body']);
386                         if ($extracted['images']) {
387                                 $message['body'] = item_redir_and_replace_images($extracted['body'], $extracted['images'], $message['contact-id']);
388                         }
389
390                         $from_name_e = $message['from-name'];
391                         $subject_e = $message['title'];
392                         $body_e = BBCode::convert($message['body']);
393                         $to_name_e = $message['name'];
394
395                         $contact = Contact::getByURL($message['from-url'], false, ['thumb', 'addr', 'id', 'avatar']);
396                         $from_photo = Contact::getThumb($contact, $message['from-photo']);
397
398                         $mails[] = [
399                                 'id' => $message['id'],
400                                 'from_name' => $from_name_e,
401                                 'from_url' => $from_url,
402                                 'from_addr' => $contact['addr'],
403                                 'sparkle' => $sparkle,
404                                 'from_photo' => $from_photo,
405                                 'subject' => $subject_e,
406                                 'body' => $body_e,
407                                 'delete' => DI::l10n()->t('Delete message'),
408                                 'to_name' => $to_name_e,
409                                 'date' => DateTimeFormat::local($message['created'], DI::l10n()->t('D, d M Y - g:i A')),
410                                 'ago' => Temporal::getRelativeDate($message['created']),
411                         ];
412
413                         $seen = $message['seen'];
414                 }
415
416                 $select = $message['name'] . '<input type="hidden" name="messageto" value="' . $contact_id . '" />';
417                 $parent = '<input type="hidden" name="replyto" value="' . $message['parent-uri'] . '" />';
418
419                 $tpl = Renderer::getMarkupTemplate('mail_display.tpl');
420                 $o = Renderer::replaceMacros($tpl, [
421                         '$thread_id' => $a->argv[1],
422                         '$thread_subject' => $message['title'],
423                         '$thread_seen' => $seen,
424                         '$delete' => DI::l10n()->t('Delete conversation'),
425                         '$canreply' => (($unknown) ? false : '1'),
426                         '$unknown_text' => DI::l10n()->t("No secure communications available. You <strong>may</strong> be able to respond from the sender's profile page."),
427                         '$mails' => $mails,
428
429                         // reply
430                         '$header' => DI::l10n()->t('Send Reply'),
431                         '$to' => DI::l10n()->t('To:'),
432                         '$showinputs' => '',
433                         '$subject' => DI::l10n()->t('Subject:'),
434                         '$subjtxt' => $message['title'],
435                         '$readonly' => ' readonly="readonly" style="background: #BBBBBB;" ',
436                         '$yourmessage' => DI::l10n()->t('Your message:'),
437                         '$text' => '',
438                         '$select' => $select,
439                         '$parent' => $parent,
440                         '$upload' => DI::l10n()->t('Upload photo'),
441                         '$insert' => DI::l10n()->t('Insert web link'),
442                         '$submit' => DI::l10n()->t('Submit'),
443                         '$wait' => DI::l10n()->t('Please wait')
444                 ]);
445
446                 return $o;
447         }
448 }
449
450 /**
451  * @param int $uid
452  * @param int $start
453  * @param int $limit
454  * @return array
455  */
456 function get_messages($uid, $start, $limit)
457 {
458         return DBA::toArray(DBA::p('SELECT
459                         m.`id`,
460                         m.`uid`,
461                         m.`guid`,
462                         m.`from-name`,
463                         m.`from-photo`,
464                         m.`from-url`,
465                         m.`contact-id`,
466                         m.`convid`,
467                         m.`title`,
468                         m.`body`,
469                         m.`seen`,
470                         m.`reply`,
471                         m.`replied`,
472                         m.`unknown`,
473                         m.`uri`,
474                         m.`parent-uri`,
475                         m.`created`,
476                         c.`name`,
477                         c.`url`,
478                         c.`thumb`,
479                         c.`network`,
480                 m2.`count`,
481                 m2.`mailcreated`,
482                 m2.`mailseen`
483         FROM `mail` m
484         JOIN (
485                 SELECT
486                         `parent-uri`,
487                     MIN(`id`)      AS `id`,
488                     COUNT(*)       AS `count`,
489                     MAX(`created`) AS `mailcreated`,
490                     MIN(`seen`)    AS `mailseen`
491                 FROM `mail`
492                 WHERE `uid` = ?
493                 GROUP BY `parent-uri`
494         ) m2 ON m.`parent-uri` = m2.`parent-uri` AND m.`id` = m2.`id`
495                 LEFT JOIN `contact` c ON m.`contact-id` = c.`id`
496                 WHERE m.`uid` = ?
497                 ORDER BY m2.`mailcreated` DESC
498                 LIMIT ?, ?'
499                 , $uid, $uid, $start, $limit));
500 }
501
502 function render_messages(array $msg, $t)
503 {
504         $a = DI::app();
505
506         $tpl = Renderer::getMarkupTemplate($t);
507         $rslt = '';
508
509         $myprofile = DI::baseUrl() . '/profile/' . $a->user['nickname'];
510
511         foreach ($msg as $rr) {
512                 if ($rr['unknown']) {
513                         $participants = DI::l10n()->t("Unknown sender - %s", $rr['from-name']);
514                 } elseif (Strings::compareLink($rr['from-url'], $myprofile)) {
515                         $participants = DI::l10n()->t("You and %s", $rr['name']);
516                 } else {
517                         $participants = DI::l10n()->t("%s and You", $rr['from-name']);
518                 }
519
520                 $body_e = $rr['body'];
521                 $to_name_e = $rr['name'];
522
523                 $contact = Contact::getByURL($rr['url'], false, ['thumb', 'addr', 'id', 'avatar']);
524                 $from_photo = Contact::getThumb($contact, $rr['thumb'] ?: $rr['from-photo']);
525
526                 $rslt .= Renderer::replaceMacros($tpl, [
527                         '$id' => $rr['id'],
528                         '$from_name' => $participants,
529                         '$from_url' => Contact::magicLink($rr['url']),
530                         '$from_addr' => $contact['addr'] ?? '',
531                         '$sparkle' => ' sparkle',
532                         '$from_photo' => $from_photo,
533                         '$subject' => $rr['title'],
534                         '$delete' => DI::l10n()->t('Delete conversation'),
535                         '$body' => $body_e,
536                         '$to_name' => $to_name_e,
537                         '$date' => DateTimeFormat::local($rr['mailcreated'], DI::l10n()->t('D, d M Y - g:i A')),
538                         '$ago' => Temporal::getRelativeDate($rr['mailcreated']),
539                         '$seen' => $rr['mailseen'],
540                         '$count' => DI::l10n()->tt('%d message', '%d messages', $rr['count']),
541                 ]);
542         }
543
544         return $rslt;
545 }