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