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