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