]> git.mxchange.org Git - friendica.git/blob - mod/message.php
mod/message return to conversation if message deleted
[friendica.git] / mod / message.php
1 <?php
2 /**
3  * @file mod/message.php
4  */
5
6 use Friendica\App;
7 use Friendica\Content\Nav;
8 use Friendica\Content\Smilies;
9 use Friendica\Content\Text\BBCode;
10 use Friendica\Core\ACL;
11 use Friendica\Core\L10n;
12 use Friendica\Core\System;
13 use Friendica\Database\DBA;
14 use Friendica\Model\Contact;
15 use Friendica\Model\Mail;
16 use Friendica\Util\DateTimeFormat;
17 use Friendica\Util\Proxy as ProxyUtils;
18 use Friendica\Util\Temporal;
19
20 require_once 'include/conversation.php';
21
22 function message_init(App $a)
23 {
24         $tabs = '';
25
26         if ($a->argc > 1 && is_numeric($a->argv[1])) {
27                 $tabs = render_messages(get_messages(local_user(), 0, 5), 'mail_list.tpl');
28         }
29
30         $new = [
31                 'label' => L10n::t('New Message'),
32                 'url' => 'message/new',
33                 'sel' => $a->argc > 1 && $a->argv[1] == 'new',
34                 'accesskey' => 'm',
35         ];
36
37         $tpl = get_markup_template('message_side.tpl');
38         $a->page['aside'] = replace_macros($tpl, [
39                 '$tabs' => $tabs,
40                 '$new' => $new,
41         ]);
42         $base = System::baseUrl();
43
44         $head_tpl = get_markup_template('message-head.tpl');
45         $a->page['htmlhead'] .= replace_macros($head_tpl, [
46                 '$baseurl' => System::baseUrl(true),
47                 '$base' => $base
48         ]);
49
50         $end_tpl = get_markup_template('message-end.tpl');
51         $a->page['end'] .= replace_macros($end_tpl, [
52                 '$baseurl' => System::baseUrl(true),
53                 '$base' => $base
54         ]);
55 }
56
57 function message_post(App $a)
58 {
59         if (!local_user()) {
60                 notice(L10n::t('Permission denied.') . EOL);
61                 return;
62         }
63
64         $replyto   = x($_REQUEST, 'replyto')   ? notags(trim($_REQUEST['replyto']))   : '';
65         $subject   = x($_REQUEST, 'subject')   ? notags(trim($_REQUEST['subject']))   : '';
66         $body      = x($_REQUEST, 'body')      ? escape_tags(trim($_REQUEST['body'])) : '';
67         $recipient = x($_REQUEST, 'messageto') ? intval($_REQUEST['messageto'])       : 0;
68
69         $ret = Mail::send($recipient, $body, $subject, $replyto);
70         $norecip = false;
71
72         switch ($ret) {
73                 case -1:
74                         notice(L10n::t('No recipient selected.') . EOL);
75                         $norecip = true;
76                         break;
77                 case -2:
78                         notice(L10n::t('Unable to locate contact information.') . EOL);
79                         break;
80                 case -3:
81                         notice(L10n::t('Message could not be sent.') . EOL);
82                         break;
83                 case -4:
84                         notice(L10n::t('Message collection failure.') . EOL);
85                         break;
86                 default:
87                         info(L10n::t('Message sent.') . EOL);
88         }
89
90         // fake it to go back to the input form if no recipient listed
91         if ($norecip) {
92                 $a->argc = 2;
93                 $a->argv[1] = 'new';
94         } else {
95                 goaway($a->cmd . '/' . $ret);
96         }
97 }
98
99 function message_content(App $a)
100 {
101         $o = '';
102         Nav::setSelected('messages');
103
104         if (!local_user()) {
105                 notice(L10n::t('Permission denied.') . EOL);
106                 return;
107         }
108
109         $myprofile = System::baseUrl() . '/profile/' . $a->user['nickname'];
110
111         $tpl = get_markup_template('mail_head.tpl');
112         if ($a->argc > 1 && $a->argv[1] == 'new') {
113                 $button = [
114                         'label' => L10n::t('Discard'),
115                         'url' => '/message',
116                         'sel' => 'close',
117                 ];
118         } else {
119                 $button = [
120                         'label' => L10n::t('New Message'),
121                         'url' => '/message/new',
122                         'sel' => 'new',
123                         'accesskey' => 'm',
124                 ];
125         }
126         $header = replace_macros($tpl, [
127                 '$messages' => L10n::t('Messages'),
128                 '$button' => $button,
129         ]);
130
131         if (($a->argc == 3) && ($a->argv[1] === 'drop' || $a->argv[1] === 'dropconv')) {
132                 if (!intval($a->argv[2])) {
133                         return;
134                 }
135
136                 // Check if we should do HTML-based delete confirmation
137                 if (!empty($_REQUEST['confirm'])) {
138                         // <form> can't take arguments in its "action" parameter
139                         // so add any arguments as hidden inputs
140                         $query = explode_querystring($a->query_string);
141                         $inputs = [];
142                         foreach ($query['args'] as $arg) {
143                                 if (strpos($arg, 'confirm=') === false) {
144                                         $arg_parts = explode('=', $arg);
145                                         $inputs[] = ['name' => $arg_parts[0], 'value' => $arg_parts[1]];
146                                 }
147                         }
148
149                         //$a->page['aside'] = '';
150                         return replace_macros(get_markup_template('confirm.tpl'), [
151                                 '$method' => 'get',
152                                 '$message' => L10n::t('Do you really want to delete this message?'),
153                                 '$extra_inputs' => $inputs,
154                                 '$confirm' => L10n::t('Yes'),
155                                 '$confirm_url' => $query['base'],
156                                 '$confirm_name' => 'confirmed',
157                                 '$cancel' => L10n::t('Cancel'),
158                         ]);
159                 }
160
161                 // Now check how the user responded to the confirmation query
162                 if (!empty($_REQUEST['canceled'])) {
163                         goaway('/message');
164                 }
165
166                 $cmd = $a->argv[1];
167                 if ($cmd === 'drop') {
168                         $r = DBA::SelectFirst('mail', ['convid'], ['id' => $a->argv[2], 'uid' => local_user()]);
169                         if(!DBA::isResult($r)){
170                                 info(L10n::t('Conversation not founded.') . EOL);
171                                 goaway('/message');
172                         }
173
174                         if (DBA::delete('mail', ['id' => $a->argv[2], 'uid' => local_user()])) {
175                                 info(L10n::t('Message deleted.') . EOL);
176                         }
177
178                         $rr = DBA::SelectFirst('mail', ['id'], ['convid' => $r['convid'], 'uid' => local_user()]);
179                         if(!DBA::isResult($rr)){
180                                 info(L10n::t('Conversation removed.') . EOL);
181                                 goaway('/message');
182                         }
183
184                         goaway('/message/'.$rr['id'] );
185                 } else {
186                         $r = q("SELECT `parent-uri`,`convid` FROM `mail` WHERE `id` = %d AND `uid` = %d LIMIT 1",
187                                 intval($a->argv[2]),
188                                 intval(local_user())
189                         );
190                         if (DBA::isResult($r)) {
191                                 $parent = $r[0]['parent-uri'];
192                                 $convid = $r[0]['convid'];
193
194                                 if (DBA::delete('mail', ['parent-uri' => $parent, 'uid' => local_user()])) {
195                                         info(L10n::t('Conversation removed.') . EOL);
196                                 }
197                         }
198                         goaway('/message' );
199                 }
200         }
201
202         if (($a->argc > 1) && ($a->argv[1] === 'new')) {
203                 $o .= $header;
204
205                 $tpl = get_markup_template('msg-header.tpl');
206                 $a->page['htmlhead'] .= replace_macros($tpl, [
207                         '$baseurl' => System::baseUrl(true),
208                         '$nickname' => $a->user['nickname'],
209                         '$linkurl' => L10n::t('Please enter a link URL:')
210                 ]);
211
212                 $tpl = get_markup_template('msg-end.tpl');
213                 $a->page['end'] .= replace_macros($tpl, [
214                         '$baseurl' => System::baseUrl(true),
215                         '$nickname' => $a->user['nickname'],
216                         '$linkurl' => 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(normalise_link(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                                 $preurl = $r[0]['url'];
245                                 $preid = $r[0]['id'];
246                                 $preselect = [$preid];
247                         } else {
248                                 $preselect = [];
249                         }
250                 }
251
252                 $prefill = $preselect ? $prename : '';
253
254                 // the ugly select box
255                 $select = ACL::getMessageContactSelectHTML('messageto', 'message-to-select', $preselect, 4, 10);
256
257                 $tpl = get_markup_template('prv_message.tpl');
258                 $o .= replace_macros($tpl, [
259                         '$header' => L10n::t('Send Private Message'),
260                         '$to' => L10n::t('To:'),
261                         '$showinputs' => 'true',
262                         '$prefill' => $prefill,
263                         '$preid' => $preid,
264                         '$subject' => L10n::t('Subject:'),
265                         '$subjtxt' => x($_REQUEST, 'subject') ? strip_tags($_REQUEST['subject']) : '',
266                         '$text' => x($_REQUEST, 'body') ? escape_tags(htmlspecialchars($_REQUEST['body'])) : '',
267                         '$readonly' => '',
268                         '$yourmessage' => L10n::t('Your message:'),
269                         '$select' => $select,
270                         '$parent' => '',
271                         '$upload' => L10n::t('Upload photo'),
272                         '$insert' => L10n::t('Insert web link'),
273                         '$wait' => L10n::t('Please wait'),
274                         '$submit' => L10n::t('Submit')
275                 ]);
276                 return $o;
277         }
278
279
280         $_SESSION['return_url'] = $a->query_string;
281
282         if ($a->argc == 1) {
283
284                 // List messages
285
286                 $o .= $header;
287
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
293                 if (DBA::isResult($r)) {
294                         $a->set_pager_total($r[0]['total']);
295                 }
296
297                 $r = get_messages(local_user(), $a->pager['start'], $a->pager['itemspage']);
298
299                 if (!DBA::isResult($r)) {
300                         info(L10n::t('No messages.') . EOL);
301                         return $o;
302                 }
303
304                 $o .= render_messages($r, 'mail_list.tpl');
305
306                 $o .= paginate($a);
307
308                 return $o;
309         }
310
311         if (($a->argc > 1) && (intval($a->argv[1]))) {
312
313                 $o .= $header;
314
315                 $r = q("SELECT `mail`.*, `contact`.`name`, `contact`.`url`, `contact`.`thumb`
316                         FROM `mail` LEFT JOIN `contact` ON `mail`.`contact-id` = `contact`.`id`
317                         WHERE `mail`.`uid` = %d AND `mail`.`id` = %d LIMIT 1",
318                         intval(local_user()),
319                         intval($a->argv[1])
320                 );
321                 if (DBA::isResult($r)) {
322                         $contact_id = $r[0]['contact-id'];
323                         $convid = $r[0]['convid'];
324
325                         $sql_extra = sprintf(" and `mail`.`parent-uri` = '%s' ", DBA::escape($r[0]['parent-uri']));
326                         if ($convid)
327                                 $sql_extra = sprintf(" and ( `mail`.`parent-uri` = '%s' OR `mail`.`convid` = '%d' ) ",
328                                         DBA::escape($r[0]['parent-uri']),
329                                         intval($convid)
330                                 );
331
332                         $messages = q("SELECT `mail`.*, `contact`.`name`, `contact`.`url`, `contact`.`thumb`
333                                 FROM `mail` LEFT JOIN `contact` ON `mail`.`contact-id` = `contact`.`id`
334                                 WHERE `mail`.`uid` = %d $sql_extra ORDER BY `mail`.`created` ASC",
335                                 intval(local_user())
336                         );
337                 } else {
338                         $messages = false;
339                 }
340                 if (!DBA::isResult($messages)) {
341                         notice(L10n::t('Message not available.') . EOL);
342                         return $o;
343                 }
344
345                 $r = q("UPDATE `mail` SET `seen` = 1 WHERE `parent-uri` = '%s' AND `uid` = %d",
346                         DBA::escape($r[0]['parent-uri']),
347                         intval(local_user())
348                 );
349
350                 $tpl = get_markup_template('msg-header.tpl');
351                 $a->page['htmlhead'] .= replace_macros($tpl, [
352                         '$baseurl' => System::baseUrl(true),
353                         '$nickname' => $a->user['nickname'],
354                         '$linkurl' => L10n::t('Please enter a link URL:')
355                 ]);
356
357                 $tpl = get_markup_template('msg-end.tpl');
358                 $a->page['end'] .= replace_macros($tpl, [
359                         '$baseurl' => System::baseUrl(true),
360                         '$nickname' => $a->user['nickname'],
361                         '$linkurl' => L10n::t('Please enter a link URL:')
362                 ]);
363
364                 $mails = [];
365                 $seen = 0;
366                 $unknown = false;
367
368                 foreach ($messages as $message) {
369                         if ($message['unknown'])
370                                 $unknown = true;
371                         if ($message['from-url'] == $myprofile) {
372                                 $from_url = $myprofile;
373                                 $sparkle = '';
374                         } else {
375                                 $from_url = Contact::magicLink($message['from-url']);
376                                 $sparkle = ' sparkle';
377                         }
378
379                         $extracted = item_extract_images($message['body']);
380                         if ($extracted['images']) {
381                                 $message['body'] = item_redir_and_replace_images($extracted['body'], $extracted['images'], $message['contact-id']);
382                         }
383
384                         $from_name_e = $message['from-name'];
385                         $subject_e = $message['title'];
386                         $body_e = Smilies::replace(BBCode::convert($message['body']));
387                         $to_name_e = $message['name'];
388
389                         $contact = Contact::getDetailsByURL($message['from-url']);
390                         if (isset($contact["thumb"])) {
391                                 $from_photo = $contact["thumb"];
392                         } else {
393                                 $from_photo = $message['from-photo'];
394                         }
395
396                         $mails[] = [
397                                 'id' => $message['id'],
398                                 'from_name' => $from_name_e,
399                                 'from_url' => $from_url,
400                                 'from_addr' => $contact['addr'],
401                                 'sparkle' => $sparkle,
402                                 'from_photo' => ProxyUtils::proxifyUrl($from_photo, false, ProxyUtils::SIZE_THUMB),
403                                 'subject' => $subject_e,
404                                 'body' => $body_e,
405                                 'delete' => L10n::t('Delete message'),
406                                 'to_name' => $to_name_e,
407                                 'date' => DateTimeFormat::local($message['created'], L10n::t('D, d M Y - g:i A')),
408                                 'ago' => Temporal::getRelativeDate($message['created']),
409                         ];
410
411                         $seen = $message['seen'];
412                 }
413
414                 $select = $message['name'] . '<input type="hidden" name="messageto" value="' . $contact_id . '" />';
415                 $parent = '<input type="hidden" name="replyto" value="' . $message['parent-uri'] . '" />';
416
417                 $tpl = get_markup_template('mail_display.tpl');
418                 $o = replace_macros($tpl, [
419                         '$thread_id' => $a->argv[1],
420                         '$thread_subject' => $message['title'],
421                         '$thread_seen' => $seen,
422                         '$delete' => L10n::t('Delete conversation'),
423                         '$canreply' => (($unknown) ? false : '1'),
424                         '$unknown_text' => L10n::t("No secure communications available. You <strong>may</strong> be able to respond from the sender's profile page."),
425                         '$mails' => $mails,
426
427                         // reply
428                         '$header' => L10n::t('Send Reply'),
429                         '$to' => L10n::t('To:'),
430                         '$showinputs' => '',
431                         '$subject' => L10n::t('Subject:'),
432                         '$subjtxt' => $message['title'],
433                         '$readonly' => ' readonly="readonly" style="background: #BBBBBB;" ',
434                         '$yourmessage' => L10n::t('Your message:'),
435                         '$text' => '',
436                         '$select' => $select,
437                         '$parent' => $parent,
438                         '$upload' => L10n::t('Upload photo'),
439                         '$insert' => L10n::t('Insert web link'),
440                         '$submit' => L10n::t('Submit'),
441                         '$wait' => L10n::t('Please wait')
442                 ]);
443
444                 return $o;
445         }
446 }
447
448 function get_messages($user, $lstart, $lend)
449 {
450         //TODO: rewritte with a sub-query to get the first message of each private thread with certainty
451         return q("SELECT max(`mail`.`created`) AS `mailcreated`, min(`mail`.`seen`) AS `mailseen`,
452                 ANY_VALUE(`mail`.`id`) AS `id`, ANY_VALUE(`mail`.`uid`) AS `uid`, ANY_VALUE(`mail`.`guid`) AS `guid`,
453                 ANY_VALUE(`mail`.`from-name`) AS `from-name`, ANY_VALUE(`mail`.`from-photo`) AS `from-photo`,
454                 ANY_VALUE(`mail`.`from-url`) AS `from-url`, ANY_VALUE(`mail`.`contact-id`) AS `contact-id`,
455                 ANY_VALUE(`mail`.`convid`) AS `convid`, ANY_VALUE(`mail`.`title`) AS `title`, ANY_VALUE(`mail`.`body`) AS `body`,
456                 ANY_VALUE(`mail`.`seen`) AS `seen`, ANY_VALUE(`mail`.`reply`) AS `reply`, ANY_VALUE(`mail`.`replied`) AS `replied`,
457                 ANY_VALUE(`mail`.`unknown`) AS `unknown`, ANY_VALUE(`mail`.`uri`) AS `uri`,
458                 `mail`.`parent-uri`,
459                 ANY_VALUE(`mail`.`created`) AS `created`, ANY_VALUE(`contact`.`name`) AS `name`, ANY_VALUE(`contact`.`url`) AS `url`,
460                 ANY_VALUE(`contact`.`thumb`) AS `thumb`, ANY_VALUE(`contact`.`network`) AS `network`,
461                 count( * ) as `count`
462                 FROM `mail` LEFT JOIN `contact` ON `mail`.`contact-id` = `contact`.`id`
463                 WHERE `mail`.`uid` = %d GROUP BY `parent-uri` ORDER BY `mailcreated` DESC LIMIT %d , %d ",
464                 intval($user), intval($lstart), intval($lend)
465         );
466 }
467
468 function render_messages(array $msg, $t)
469 {
470         $a = get_app();
471
472         $tpl = get_markup_template($t);
473         $rslt = '';
474
475         $myprofile = System::baseUrl() . '/profile/' . $a->user['nickname'];
476
477         foreach ($msg as $rr) {
478                 if ($rr['unknown']) {
479                         $participants = L10n::t("Unknown sender - %s", $rr['from-name']);
480                 } elseif (link_compare($rr['from-url'], $myprofile)) {
481                         $participants = L10n::t("You and %s", $rr['name']);
482                 } else {
483                         $participants = L10n::t("%s and You", $rr['from-name']);
484                 }
485
486                 $subject_e = (($rr['mailseen']) ? $rr['title'] : '<strong>' . $rr['title'] . '</strong>');
487                 $body_e = $rr['body'];
488                 $to_name_e = $rr['name'];
489
490                 $contact = Contact::getDetailsByURL($rr['url']);
491                 if (isset($contact["thumb"])) {
492                         $from_photo = $contact["thumb"];
493                 } else {
494                         $from_photo = (($rr['thumb']) ? $rr['thumb'] : $rr['from-photo']);
495                 }
496
497                 $rslt .= replace_macros($tpl, [
498                         '$id' => $rr['id'],
499                         '$from_name' => $participants,
500                         '$from_url' => Contact::magicLink($rr['url']),
501                         '$from_addr' => defaults($contact, 'addr', ''),
502                         '$sparkle' => ' sparkle',
503                         '$from_photo' => ProxyUtils::proxifyUrl($from_photo, false, ProxyUtils::SIZE_THUMB),
504                         '$subject' => $subject_e,
505                         '$delete' => L10n::t('Delete conversation'),
506                         '$body' => $body_e,
507                         '$to_name' => $to_name_e,
508                         '$date' => DateTimeFormat::local($rr['mailcreated'], L10n::t('D, d M Y - g:i A')),
509                         '$ago' => Temporal::getRelativeDate($rr['mailcreated']),
510                         '$seen' => $rr['mailseen'],
511                         '$count' => L10n::tt('%d message', '%d messages', $rr['count']),
512                 ]);
513         }
514
515         return $rslt;
516 }