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