]> git.mxchange.org Git - friendica.git/blob - mod/message.php
Merge pull request #8883 from annando/replace-getdetails
[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::l10n(), 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                         DBA::update('notify', ['seen' => 1], ['type' => Type::MAIL, 'parent' => $message['id'], 'uid' => local_user()]);
356                 } else {
357                         $messages = false;
358                 }
359
360                 if (!DBA::isResult($messages)) {
361                         notice(DI::l10n()->t('Message not available.') . EOL);
362                         return $o;
363                 }
364
365                 $tpl = Renderer::getMarkupTemplate('msg-header.tpl');
366                 DI::page()['htmlhead'] .= Renderer::replaceMacros($tpl, [
367                         '$baseurl' => DI::baseUrl()->get(true),
368                         '$nickname' => $a->user['nickname'],
369                         '$linkurl' => DI::l10n()->t('Please enter a link URL:')
370                 ]);
371
372                 $mails = [];
373                 $seen = 0;
374                 $unknown = false;
375
376                 foreach ($messages as $message) {
377                         if ($message['unknown']) {
378                                 $unknown = true;
379                         }
380
381                         if ($message['from-url'] == $myprofile) {
382                                 $from_url = $myprofile;
383                                 $sparkle = '';
384                         } else {
385                                 $from_url = Contact::magicLink($message['from-url']);
386                                 $sparkle = ' sparkle';
387                         }
388
389                         $extracted = item_extract_images($message['body']);
390                         if ($extracted['images']) {
391                                 $message['body'] = item_redir_and_replace_images($extracted['body'], $extracted['images'], $message['contact-id']);
392                         }
393
394                         $from_name_e = $message['from-name'];
395                         $subject_e = $message['title'];
396                         $body_e = BBCode::convert($message['body']);
397                         $to_name_e = $message['name'];
398
399                         $contact = Contact::getByURL($message['from-url'], false, ['thumb', 'addr']);
400                         if (isset($contact["thumb"])) {
401                                 $from_photo = $contact["thumb"];
402                         } else {
403                                 $from_photo = $message['from-photo'];
404                         }
405
406                         $mails[] = [
407                                 'id' => $message['id'],
408                                 'from_name' => $from_name_e,
409                                 'from_url' => $from_url,
410                                 'from_addr' => $contact['addr'],
411                                 'sparkle' => $sparkle,
412                                 'from_photo' => ProxyUtils::proxifyUrl($from_photo, false, ProxyUtils::SIZE_THUMB),
413                                 'subject' => $subject_e,
414                                 'body' => $body_e,
415                                 'delete' => DI::l10n()->t('Delete message'),
416                                 'to_name' => $to_name_e,
417                                 'date' => DateTimeFormat::local($message['created'], DI::l10n()->t('D, d M Y - g:i A')),
418                                 'ago' => Temporal::getRelativeDate($message['created']),
419                         ];
420
421                         $seen = $message['seen'];
422                 }
423
424                 $select = $message['name'] . '<input type="hidden" name="messageto" value="' . $contact_id . '" />';
425                 $parent = '<input type="hidden" name="replyto" value="' . $message['parent-uri'] . '" />';
426
427                 $tpl = Renderer::getMarkupTemplate('mail_display.tpl');
428                 $o = Renderer::replaceMacros($tpl, [
429                         '$thread_id' => $a->argv[1],
430                         '$thread_subject' => $message['title'],
431                         '$thread_seen' => $seen,
432                         '$delete' => DI::l10n()->t('Delete conversation'),
433                         '$canreply' => (($unknown) ? false : '1'),
434                         '$unknown_text' => DI::l10n()->t("No secure communications available. You <strong>may</strong> be able to respond from the sender's profile page."),
435                         '$mails' => $mails,
436
437                         // reply
438                         '$header' => DI::l10n()->t('Send Reply'),
439                         '$to' => DI::l10n()->t('To:'),
440                         '$showinputs' => '',
441                         '$subject' => DI::l10n()->t('Subject:'),
442                         '$subjtxt' => $message['title'],
443                         '$readonly' => ' readonly="readonly" style="background: #BBBBBB;" ',
444                         '$yourmessage' => DI::l10n()->t('Your message:'),
445                         '$text' => '',
446                         '$select' => $select,
447                         '$parent' => $parent,
448                         '$upload' => DI::l10n()->t('Upload photo'),
449                         '$insert' => DI::l10n()->t('Insert web link'),
450                         '$submit' => DI::l10n()->t('Submit'),
451                         '$wait' => DI::l10n()->t('Please wait')
452                 ]);
453
454                 return $o;
455         }
456 }
457
458 /**
459  * @param int $uid
460  * @param int $start
461  * @param int $limit
462  * @return array
463  */
464 function get_messages($uid, $start, $limit)
465 {
466         return DBA::toArray(DBA::p('SELECT
467                         m.`id`,
468                         m.`uid`,
469                         m.`guid`,
470                         m.`from-name`,
471                         m.`from-photo`,
472                         m.`from-url`,
473                         m.`contact-id`,
474                         m.`convid`,
475                         m.`title`,
476                         m.`body`,
477                         m.`seen`,
478                         m.`reply`,
479                         m.`replied`,
480                         m.`unknown`,
481                         m.`uri`,
482                         m.`parent-uri`,
483                         m.`created`,
484                         c.`name`,
485                         c.`url`,
486                         c.`thumb`,
487                         c.`network`,
488                 m2.`count`,
489                 m2.`mailcreated`,
490                 m2.`mailseen`
491         FROM `mail` m
492         JOIN (
493                 SELECT
494                         `parent-uri`,
495                     MIN(`id`)      AS `id`,
496                     COUNT(*)       AS `count`,
497                     MAX(`created`) AS `mailcreated`,
498                     MIN(`seen`)    AS `mailseen`
499                 FROM `mail`
500                 WHERE `uid` = ?
501                 GROUP BY `parent-uri`
502         ) m2 ON m.`parent-uri` = m2.`parent-uri` AND m.`id` = m2.`id`
503                 LEFT JOIN `contact` c ON m.`contact-id` = c.`id`
504                 WHERE m.`uid` = ?
505                 ORDER BY m2.`mailcreated` DESC
506                 LIMIT ?, ?'
507                 , $uid, $uid, $start, $limit));
508 }
509
510 function render_messages(array $msg, $t)
511 {
512         $a = DI::app();
513
514         $tpl = Renderer::getMarkupTemplate($t);
515         $rslt = '';
516
517         $myprofile = DI::baseUrl() . '/profile/' . $a->user['nickname'];
518
519         foreach ($msg as $rr) {
520                 if ($rr['unknown']) {
521                         $participants = DI::l10n()->t("Unknown sender - %s", $rr['from-name']);
522                 } elseif (Strings::compareLink($rr['from-url'], $myprofile)) {
523                         $participants = DI::l10n()->t("You and %s", $rr['name']);
524                 } else {
525                         $participants = DI::l10n()->t("%s and You", $rr['from-name']);
526                 }
527
528                 $body_e = $rr['body'];
529                 $to_name_e = $rr['name'];
530
531                 $contact = Contact::getByURL($rr['url'], false, ['thumb', 'addr']);
532                 if (isset($contact["thumb"])) {
533                         $from_photo = $contact["thumb"];
534                 } else {
535                         $from_photo = (($rr['thumb']) ? $rr['thumb'] : $rr['from-photo']);
536                 }
537
538                 $rslt .= Renderer::replaceMacros($tpl, [
539                         '$id' => $rr['id'],
540                         '$from_name' => $participants,
541                         '$from_url' => Contact::magicLink($rr['url']),
542                         '$from_addr' => $contact['addr'] ?? '',
543                         '$sparkle' => ' sparkle',
544                         '$from_photo' => ProxyUtils::proxifyUrl($from_photo, false, ProxyUtils::SIZE_THUMB),
545                         '$subject' => $rr['title'],
546                         '$delete' => DI::l10n()->t('Delete conversation'),
547                         '$body' => $body_e,
548                         '$to_name' => $to_name_e,
549                         '$date' => DateTimeFormat::local($rr['mailcreated'], DI::l10n()->t('D, d M Y - g:i A')),
550                         '$ago' => Temporal::getRelativeDate($rr['mailcreated']),
551                         '$seen' => $rr['mailseen'],
552                         '$count' => DI::l10n()->tt('%d message', '%d messages', $rr['count']),
553                 ]);
554         }
555
556         return $rslt;
557 }