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