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