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