]> git.mxchange.org Git - friendica.git/blob - mod/message.php
Merge pull request #5773 from MrPetovan/task/rewrite-js-hooks
[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\Smilies;
9 use Friendica\Content\Text\BBCode;
10 use Friendica\Core\ACL;
11 use Friendica\Core\L10n;
12 use Friendica\Core\System;
13 use Friendica\Database\DBA;
14 use Friendica\Model\Contact;
15 use Friendica\Model\Mail;
16 use Friendica\Util\DateTimeFormat;
17 use Friendica\Util\Proxy as ProxyUtils;
18 use Friendica\Util\Temporal;
19
20 require_once 'include/conversation.php';
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' => L10n::t('New Message'),
32                 'url' => 'message/new',
33                 'sel' => $a->argc > 1 && $a->argv[1] == 'new',
34                 'accesskey' => 'm',
35         ];
36
37         $tpl = get_markup_template('message_side.tpl');
38         $a->page['aside'] = replace_macros($tpl, [
39                 '$tabs' => $tabs,
40                 '$new' => $new,
41         ]);
42         $base = System::baseUrl();
43
44         $head_tpl = get_markup_template('message-head.tpl');
45         $a->page['htmlhead'] .= replace_macros($head_tpl, [
46                 '$baseurl' => System::baseUrl(true),
47                 '$base' => $base
48         ]);
49 }
50
51 function message_post(App $a)
52 {
53         if (!local_user()) {
54                 notice(L10n::t('Permission denied.') . EOL);
55                 return;
56         }
57
58         $replyto   = x($_REQUEST, 'replyto')   ? notags(trim($_REQUEST['replyto']))   : '';
59         $subject   = x($_REQUEST, 'subject')   ? notags(trim($_REQUEST['subject']))   : '';
60         $body      = x($_REQUEST, 'body')      ? escape_tags(trim($_REQUEST['body'])) : '';
61         $recipient = x($_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(L10n::t('No recipient selected.') . EOL);
69                         $norecip = true;
70                         break;
71                 case -2:
72                         notice(L10n::t('Unable to locate contact information.') . EOL);
73                         break;
74                 case -3:
75                         notice(L10n::t('Message could not be sent.') . EOL);
76                         break;
77                 case -4:
78                         notice(L10n::t('Message collection failure.') . EOL);
79                         break;
80                 default:
81                         info(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                 goaway($a->cmd . '/' . $ret);
90         }
91 }
92
93 function message_content(App $a)
94 {
95         $o = '';
96         Nav::setSelected('messages');
97
98         if (!local_user()) {
99                 notice(L10n::t('Permission denied.') . EOL);
100                 return;
101         }
102
103         $myprofile = System::baseUrl() . '/profile/' . $a->user['nickname'];
104
105         $tpl = get_markup_template('mail_head.tpl');
106         if ($a->argc > 1 && $a->argv[1] == 'new') {
107                 $button = [
108                         'label' => L10n::t('Discard'),
109                         'url' => '/message',
110                         'sel' => 'close',
111                 ];
112         } else {
113                 $button = [
114                         'label' => L10n::t('New Message'),
115                         'url' => '/message/new',
116                         'sel' => 'new',
117                         'accesskey' => 'm',
118                 ];
119         }
120         $header = replace_macros($tpl, [
121                 '$messages' => 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($a->query_string);
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                         //$a->page['aside'] = '';
144                         return replace_macros(get_markup_template('confirm.tpl'), [
145                                 '$method' => 'get',
146                                 '$message' => L10n::t('Do you really want to delete this message?'),
147                                 '$extra_inputs' => $inputs,
148                                 '$confirm' => L10n::t('Yes'),
149                                 '$confirm_url' => $query['base'],
150                                 '$confirm_name' => 'confirmed',
151                                 '$cancel' => L10n::t('Cancel'),
152                         ]);
153                 }
154
155                 // Now check how the user responded to the confirmation query
156                 if (!empty($_REQUEST['canceled'])) {
157                         goaway($_SESSION['return_url']);
158                 }
159
160                 $cmd = $a->argv[1];
161                 if ($cmd === 'drop') {
162                         if (DBA::delete('mail', ['id' => $a->argv[2], 'uid' => local_user()])) {
163                                 info(L10n::t('Message deleted.') . EOL);
164                         }
165
166                         //goaway(System::baseUrl(true) . '/message' );
167                         goaway($_SESSION['return_url']);
168                 } else {
169                         $r = q("SELECT `parent-uri`,`convid` FROM `mail` WHERE `id` = %d AND `uid` = %d LIMIT 1",
170                                 intval($a->argv[2]),
171                                 intval(local_user())
172                         );
173                         if (DBA::isResult($r)) {
174                                 $parent = $r[0]['parent-uri'];
175                                 $convid = $r[0]['convid'];
176
177                                 if (DBA::delete('mail', ['parent-uri' => $parent, 'uid' => local_user()])) {
178                                         info(L10n::t('Conversation removed.') . EOL);
179                                 }
180                         }
181                         //goaway(System::baseUrl(true) . '/message' );
182                         goaway($_SESSION['return_url']);
183                 }
184         }
185
186         if (($a->argc > 1) && ($a->argv[1] === 'new')) {
187                 $o .= $header;
188
189                 $tpl = get_markup_template('msg-header.tpl');
190                 $a->page['htmlhead'] .= replace_macros($tpl, [
191                         '$baseurl' => System::baseUrl(true),
192                         '$nickname' => $a->user['nickname'],
193                         '$linkurl' => L10n::t('Please enter a link URL:')
194                 ]);
195
196                 $preselect = isset($a->argv[2]) ? [$a->argv[2]] : [];
197
198                 $prename = $preurl = $preid = '';
199
200                 if ($preselect) {
201                         $r = q("SELECT `name`, `url`, `id` FROM `contact` WHERE `uid` = %d AND `id` = %d LIMIT 1",
202                                 intval(local_user()),
203                                 intval($a->argv[2])
204                         );
205                         if (!DBA::isResult($r)) {
206                                 $r = q("SELECT `name`, `url`, `id` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' LIMIT 1",
207                                         intval(local_user()),
208                                         DBA::escape(normalise_link(base64_decode($a->argv[2])))
209                                 );
210                         }
211
212                         if (!DBA::isResult($r)) {
213                                 $r = q("SELECT `name`, `url`, `id` FROM `contact` WHERE `uid` = %d AND `addr` = '%s' LIMIT 1",
214                                         intval(local_user()),
215                                         DBA::escape(base64_decode($a->argv[2]))
216                                 );
217                         }
218
219                         if (DBA::isResult($r)) {
220                                 $prename = $r[0]['name'];
221                                 $preurl = $r[0]['url'];
222                                 $preid = $r[0]['id'];
223                                 $preselect = [$preid];
224                         } else {
225                                 $preselect = [];
226                         }
227                 }
228
229                 $prefill = $preselect ? $prename : '';
230
231                 // the ugly select box
232                 $select = ACL::getMessageContactSelectHTML('messageto', 'message-to-select', $preselect, 4, 10);
233
234                 $tpl = get_markup_template('prv_message.tpl');
235                 $o .= replace_macros($tpl, [
236                         '$header' => L10n::t('Send Private Message'),
237                         '$to' => L10n::t('To:'),
238                         '$showinputs' => 'true',
239                         '$prefill' => $prefill,
240                         '$preid' => $preid,
241                         '$subject' => L10n::t('Subject:'),
242                         '$subjtxt' => x($_REQUEST, 'subject') ? strip_tags($_REQUEST['subject']) : '',
243                         '$text' => x($_REQUEST, 'body') ? escape_tags(htmlspecialchars($_REQUEST['body'])) : '',
244                         '$readonly' => '',
245                         '$yourmessage' => L10n::t('Your message:'),
246                         '$select' => $select,
247                         '$parent' => '',
248                         '$upload' => L10n::t('Upload photo'),
249                         '$insert' => L10n::t('Insert web link'),
250                         '$wait' => L10n::t('Please wait'),
251                         '$submit' => L10n::t('Submit')
252                 ]);
253                 return $o;
254         }
255
256
257         $_SESSION['return_url'] = $a->query_string;
258
259         if ($a->argc == 1) {
260
261                 // List messages
262
263                 $o .= $header;
264
265                 $r = q("SELECT count(*) AS `total`, ANY_VALUE(`created`) AS `created` FROM `mail`
266                         WHERE `mail`.`uid` = %d GROUP BY `parent-uri` ORDER BY `created` DESC",
267                         intval(local_user())
268                 );
269
270                 if (DBA::isResult($r)) {
271                         $a->set_pager_total($r[0]['total']);
272                 }
273
274                 $r = get_messages(local_user(), $a->pager['start'], $a->pager['itemspage']);
275
276                 if (!DBA::isResult($r)) {
277                         info(L10n::t('No messages.') . EOL);
278                         return $o;
279                 }
280
281                 $o .= render_messages($r, 'mail_list.tpl');
282
283                 $o .= paginate($a);
284
285                 return $o;
286         }
287
288         if (($a->argc > 1) && (intval($a->argv[1]))) {
289
290                 $o .= $header;
291
292                 $r = q("SELECT `mail`.*, `contact`.`name`, `contact`.`url`, `contact`.`thumb`
293                         FROM `mail` LEFT JOIN `contact` ON `mail`.`contact-id` = `contact`.`id`
294                         WHERE `mail`.`uid` = %d AND `mail`.`id` = %d LIMIT 1",
295                         intval(local_user()),
296                         intval($a->argv[1])
297                 );
298                 if (DBA::isResult($r)) {
299                         $contact_id = $r[0]['contact-id'];
300                         $convid = $r[0]['convid'];
301
302                         $sql_extra = sprintf(" and `mail`.`parent-uri` = '%s' ", DBA::escape($r[0]['parent-uri']));
303                         if ($convid)
304                                 $sql_extra = sprintf(" and ( `mail`.`parent-uri` = '%s' OR `mail`.`convid` = '%d' ) ",
305                                         DBA::escape($r[0]['parent-uri']),
306                                         intval($convid)
307                                 );
308
309                         $messages = q("SELECT `mail`.*, `contact`.`name`, `contact`.`url`, `contact`.`thumb`
310                                 FROM `mail` LEFT JOIN `contact` ON `mail`.`contact-id` = `contact`.`id`
311                                 WHERE `mail`.`uid` = %d $sql_extra ORDER BY `mail`.`created` ASC",
312                                 intval(local_user())
313                         );
314                 } else {
315                         $messages = false;
316                 }
317                 if (!DBA::isResult($messages)) {
318                         notice(L10n::t('Message not available.') . EOL);
319                         return $o;
320                 }
321
322                 $r = q("UPDATE `mail` SET `seen` = 1 WHERE `parent-uri` = '%s' AND `uid` = %d",
323                         DBA::escape($r[0]['parent-uri']),
324                         intval(local_user())
325                 );
326
327                 $tpl = get_markup_template('msg-header.tpl');
328                 $a->page['htmlhead'] .= replace_macros($tpl, [
329                         '$baseurl' => System::baseUrl(true),
330                         '$nickname' => $a->user['nickname'],
331                         '$linkurl' => L10n::t('Please enter a link URL:')
332                 ]);
333
334                 $mails = [];
335                 $seen = 0;
336                 $unknown = false;
337
338                 foreach ($messages as $message) {
339                         if ($message['unknown'])
340                                 $unknown = true;
341                         if ($message['from-url'] == $myprofile) {
342                                 $from_url = $myprofile;
343                                 $sparkle = '';
344                         } else {
345                                 $from_url = Contact::magicLink($message['from-url']);
346                                 $sparkle = ' sparkle';
347                         }
348
349                         $extracted = item_extract_images($message['body']);
350                         if ($extracted['images']) {
351                                 $message['body'] = item_redir_and_replace_images($extracted['body'], $extracted['images'], $message['contact-id']);
352                         }
353
354                         $from_name_e = $message['from-name'];
355                         $subject_e = $message['title'];
356                         $body_e = Smilies::replace(BBCode::convert($message['body']));
357                         $to_name_e = $message['name'];
358
359                         $contact = Contact::getDetailsByURL($message['from-url']);
360                         if (isset($contact["thumb"])) {
361                                 $from_photo = $contact["thumb"];
362                         } else {
363                                 $from_photo = $message['from-photo'];
364                         }
365
366                         $mails[] = [
367                                 'id' => $message['id'],
368                                 'from_name' => $from_name_e,
369                                 'from_url' => $from_url,
370                                 'from_addr' => $contact['addr'],
371                                 'sparkle' => $sparkle,
372                                 'from_photo' => ProxyUtils::proxifyUrl($from_photo, false, ProxyUtils::SIZE_THUMB),
373                                 'subject' => $subject_e,
374                                 'body' => $body_e,
375                                 'delete' => L10n::t('Delete message'),
376                                 'to_name' => $to_name_e,
377                                 'date' => DateTimeFormat::local($message['created'], L10n::t('D, d M Y - g:i A')),
378                                 'ago' => Temporal::getRelativeDate($message['created']),
379                         ];
380
381                         $seen = $message['seen'];
382                 }
383
384                 $select = $message['name'] . '<input type="hidden" name="messageto" value="' . $contact_id . '" />';
385                 $parent = '<input type="hidden" name="replyto" value="' . $message['parent-uri'] . '" />';
386
387                 $tpl = get_markup_template('mail_display.tpl');
388                 $o = replace_macros($tpl, [
389                         '$thread_id' => $a->argv[1],
390                         '$thread_subject' => $message['title'],
391                         '$thread_seen' => $seen,
392                         '$delete' => L10n::t('Delete conversation'),
393                         '$canreply' => (($unknown) ? false : '1'),
394                         '$unknown_text' => L10n::t("No secure communications available. You <strong>may</strong> be able to respond from the sender's profile page."),
395                         '$mails' => $mails,
396
397                         // reply
398                         '$header' => L10n::t('Send Reply'),
399                         '$to' => L10n::t('To:'),
400                         '$showinputs' => '',
401                         '$subject' => L10n::t('Subject:'),
402                         '$subjtxt' => $message['title'],
403                         '$readonly' => ' readonly="readonly" style="background: #BBBBBB;" ',
404                         '$yourmessage' => L10n::t('Your message:'),
405                         '$text' => '',
406                         '$select' => $select,
407                         '$parent' => $parent,
408                         '$upload' => L10n::t('Upload photo'),
409                         '$insert' => L10n::t('Insert web link'),
410                         '$submit' => L10n::t('Submit'),
411                         '$wait' => L10n::t('Please wait')
412                 ]);
413
414                 return $o;
415         }
416 }
417
418 function get_messages($user, $lstart, $lend)
419 {
420         //TODO: rewritte with a sub-query to get the first message of each private thread with certainty
421         return q("SELECT max(`mail`.`created`) AS `mailcreated`, min(`mail`.`seen`) AS `mailseen`,
422                 ANY_VALUE(`mail`.`id`) AS `id`, ANY_VALUE(`mail`.`uid`) AS `uid`, ANY_VALUE(`mail`.`guid`) AS `guid`,
423                 ANY_VALUE(`mail`.`from-name`) AS `from-name`, ANY_VALUE(`mail`.`from-photo`) AS `from-photo`,
424                 ANY_VALUE(`mail`.`from-url`) AS `from-url`, ANY_VALUE(`mail`.`contact-id`) AS `contact-id`,
425                 ANY_VALUE(`mail`.`convid`) AS `convid`, ANY_VALUE(`mail`.`title`) AS `title`, ANY_VALUE(`mail`.`body`) AS `body`,
426                 ANY_VALUE(`mail`.`seen`) AS `seen`, ANY_VALUE(`mail`.`reply`) AS `reply`, ANY_VALUE(`mail`.`replied`) AS `replied`,
427                 ANY_VALUE(`mail`.`unknown`) AS `unknown`, ANY_VALUE(`mail`.`uri`) AS `uri`,
428                 `mail`.`parent-uri`,
429                 ANY_VALUE(`mail`.`created`) AS `created`, ANY_VALUE(`contact`.`name`) AS `name`, ANY_VALUE(`contact`.`url`) AS `url`,
430                 ANY_VALUE(`contact`.`thumb`) AS `thumb`, ANY_VALUE(`contact`.`network`) AS `network`,
431                 count( * ) as `count`
432                 FROM `mail` LEFT JOIN `contact` ON `mail`.`contact-id` = `contact`.`id`
433                 WHERE `mail`.`uid` = %d GROUP BY `parent-uri` ORDER BY `mailcreated` DESC LIMIT %d , %d ",
434                 intval($user), intval($lstart), intval($lend)
435         );
436 }
437
438 function render_messages(array $msg, $t)
439 {
440         $a = get_app();
441
442         $tpl = get_markup_template($t);
443         $rslt = '';
444
445         $myprofile = System::baseUrl() . '/profile/' . $a->user['nickname'];
446
447         foreach ($msg as $rr) {
448                 if ($rr['unknown']) {
449                         $participants = L10n::t("Unknown sender - %s", $rr['from-name']);
450                 } elseif (link_compare($rr['from-url'], $myprofile)) {
451                         $participants = L10n::t("You and %s", $rr['name']);
452                 } else {
453                         $participants = L10n::t("%s and You", $rr['from-name']);
454                 }
455
456                 $subject_e = (($rr['mailseen']) ? $rr['title'] : '<strong>' . $rr['title'] . '</strong>');
457                 $body_e = $rr['body'];
458                 $to_name_e = $rr['name'];
459
460                 $contact = Contact::getDetailsByURL($rr['url']);
461                 if (isset($contact["thumb"])) {
462                         $from_photo = $contact["thumb"];
463                 } else {
464                         $from_photo = (($rr['thumb']) ? $rr['thumb'] : $rr['from-photo']);
465                 }
466
467                 $rslt .= replace_macros($tpl, [
468                         '$id' => $rr['id'],
469                         '$from_name' => $participants,
470                         '$from_url' => Contact::magicLink($rr['url']),
471                         '$from_addr' => defaults($contact, 'addr', ''),
472                         '$sparkle' => ' sparkle',
473                         '$from_photo' => ProxyUtils::proxifyUrl($from_photo, false, ProxyUtils::SIZE_THUMB),
474                         '$subject' => $subject_e,
475                         '$delete' => L10n::t('Delete conversation'),
476                         '$body' => $body_e,
477                         '$to_name' => $to_name_e,
478                         '$date' => DateTimeFormat::local($rr['mailcreated'], L10n::t('D, d M Y - g:i A')),
479                         '$ago' => Temporal::getRelativeDate($rr['mailcreated']),
480                         '$seen' => $rr['mailseen'],
481                         '$count' => L10n::tt('%d message', '%d messages', $rr['count']),
482                 ]);
483         }
484
485         return $rslt;
486 }