]> git.mxchange.org Git - friendica.git/blob - mod/message.php
Merge pull request #9444 from annando/update
[friendica.git] / mod / message.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2020, Friendica
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 use Friendica\App;
23 use Friendica\Content\Nav;
24 use Friendica\Content\Pager;
25 use Friendica\Content\Text\BBCode;
26 use Friendica\Core\ACL;
27 use Friendica\Core\Renderer;
28 use Friendica\Database\DBA;
29 use Friendica\DI;
30 use Friendica\Model\Contact;
31 use Friendica\Model\Mail;
32 use Friendica\Model\Notify\Type;
33 use Friendica\Module\Security\Login;
34 use Friendica\Util\DateTimeFormat;
35 use Friendica\Util\Strings;
36 use Friendica\Util\Temporal;
37
38 function message_init(App $a)
39 {
40         $tabs = '';
41
42         if ($a->argc > 1 && is_numeric($a->argv[1])) {
43                 $tabs = render_messages(get_messages(local_user(), 0, 5), 'mail_list.tpl');
44         }
45
46         $new = [
47                 'label' => DI::l10n()->t('New Message'),
48                 'url' => 'message/new',
49                 'sel' => $a->argc > 1 && $a->argv[1] == 'new',
50                 'accesskey' => 'm',
51         ];
52
53         $tpl = Renderer::getMarkupTemplate('message_side.tpl');
54         DI::page()['aside'] = Renderer::replaceMacros($tpl, [
55                 '$tabs' => $tabs,
56                 '$new' => $new,
57         ]);
58         $base = DI::baseUrl();
59
60         $head_tpl = Renderer::getMarkupTemplate('message-head.tpl');
61         DI::page()['htmlhead'] .= Renderer::replaceMacros($head_tpl, [
62                 '$baseurl' => DI::baseUrl()->get(true),
63                 '$base' => $base
64         ]);
65 }
66
67 function message_post(App $a)
68 {
69         if (!local_user()) {
70                 notice(DI::l10n()->t('Permission denied.'));
71                 return;
72         }
73
74         $replyto   = !empty($_REQUEST['replyto'])   ? Strings::escapeTags(trim($_REQUEST['replyto'])) : '';
75         $subject   = !empty($_REQUEST['subject'])   ? Strings::escapeTags(trim($_REQUEST['subject'])) : '';
76         $body      = !empty($_REQUEST['body'])      ? Strings::escapeHtml(trim($_REQUEST['body']))    : '';
77         $recipient = !empty($_REQUEST['recipient']) ? intval($_REQUEST['recipient'])                  : 0;
78
79         $ret = Mail::send($recipient, $body, $subject, $replyto);
80         $norecip = false;
81
82         switch ($ret) {
83                 case -1:
84                         notice(DI::l10n()->t('No recipient selected.'));
85                         $norecip = true;
86                         break;
87                 case -2:
88                         notice(DI::l10n()->t('Unable to locate contact information.'));
89                         break;
90                 case -3:
91                         notice(DI::l10n()->t('Message could not be sent.'));
92                         break;
93                 case -4:
94                         notice(DI::l10n()->t('Message collection failure.'));
95                         break;
96         }
97
98         // fake it to go back to the input form if no recipient listed
99         if ($norecip) {
100                 $a->argc = 2;
101                 $a->argv[1] = 'new';
102         } else {
103                 DI::baseUrl()->redirect(DI::args()->getCommand() . '/' . $ret);
104         }
105 }
106
107 function message_content(App $a)
108 {
109         $o = '';
110         Nav::setSelected('messages');
111
112         if (!local_user()) {
113                 notice(DI::l10n()->t('Permission denied.'));
114                 return Login::form();
115         }
116
117         $myprofile = DI::baseUrl() . '/profile/' . $a->user['nickname'];
118
119         $tpl = Renderer::getMarkupTemplate('mail_head.tpl');
120         if ($a->argc > 1 && $a->argv[1] == 'new') {
121                 $button = [
122                         'label' => DI::l10n()->t('Discard'),
123                         'url' => '/message',
124                         'sel' => 'close',
125                 ];
126         } else {
127                 $button = [
128                         'label' => DI::l10n()->t('New Message'),
129                         'url' => '/message/new',
130                         'sel' => 'new',
131                         'accesskey' => 'm',
132                 ];
133         }
134         $header = Renderer::replaceMacros($tpl, [
135                 '$messages' => DI::l10n()->t('Messages'),
136                 '$button' => $button,
137         ]);
138
139         if (($a->argc == 3) && ($a->argv[1] === 'drop' || $a->argv[1] === 'dropconv')) {
140                 if (!intval($a->argv[2])) {
141                         return;
142                 }
143
144                 $cmd = $a->argv[1];
145                 if ($cmd === 'drop') {
146                         $message = DBA::selectFirst('mail', ['convid'], ['id' => $a->argv[2], 'uid' => local_user()]);
147                         if(!DBA::isResult($message)){
148                                 notice(DI::l10n()->t('Conversation not found.'));
149                                 DI::baseUrl()->redirect('message');
150                         }
151
152                         if (!DBA::delete('mail', ['id' => $a->argv[2], 'uid' => local_user()])) {
153                                 notice(DI::l10n()->t('Message was not deleted.'));
154                         }
155
156                         $conversation = DBA::selectFirst('mail', ['id'], ['convid' => $message['convid'], 'uid' => local_user()]);
157                         if(!DBA::isResult($conversation)){
158                                 DI::baseUrl()->redirect('message');
159                         }
160
161                         DI::baseUrl()->redirect('message/' . $conversation['id'] );
162                 } else {
163                         $r = q("SELECT `parent-uri`,`convid` FROM `mail` WHERE `id` = %d AND `uid` = %d LIMIT 1",
164                                 intval($a->argv[2]),
165                                 intval(local_user())
166                         );
167                         if (DBA::isResult($r)) {
168                                 $parent = $r[0]['parent-uri'];
169
170                                 if (!DBA::delete('mail', ['parent-uri' => $parent, 'uid' => local_user()])) {
171                                         notice(DI::l10n()->t('Conversation was not removed.'));
172                                 }
173                         }
174                         DI::baseUrl()->redirect('message');
175                 }
176         }
177
178         if (($a->argc > 1) && ($a->argv[1] === 'new')) {
179                 $o .= $header;
180
181                 $tpl = Renderer::getMarkupTemplate('msg-header.tpl');
182                 DI::page()['htmlhead'] .= Renderer::replaceMacros($tpl, [
183                         '$baseurl' => DI::baseUrl()->get(true),
184                         '$nickname' => $a->user['nickname'],
185                         '$linkurl' => DI::l10n()->t('Please enter a link URL:')
186                 ]);
187
188                 $recipientId = $a->argv[2] ?? null;
189
190                 $select = ACL::getMessageContactSelectHTML($recipientId);
191
192                 $tpl = Renderer::getMarkupTemplate('prv_message.tpl');
193                 $o .= Renderer::replaceMacros($tpl, [
194                         '$header'     => DI::l10n()->t('Send Private Message'),
195                         '$to'         => DI::l10n()->t('To:'),
196                         '$subject'    => DI::l10n()->t('Subject:'),
197                         '$subjtxt'    => $_REQUEST['subject'] ?? '',
198                         '$text'       => $_REQUEST['body'] ?? '',
199                         '$readonly'   => '',
200                         '$yourmessage'=> DI::l10n()->t('Your message:'),
201                         '$select'     => $select,
202                         '$parent'     => '',
203                         '$upload'     => DI::l10n()->t('Upload photo'),
204                         '$insert'     => DI::l10n()->t('Insert web link'),
205                         '$wait'       => DI::l10n()->t('Please wait'),
206                         '$submit'     => DI::l10n()->t('Submit')
207                 ]);
208                 return $o;
209         }
210
211
212         $_SESSION['return_path'] = DI::args()->getQueryString();
213
214         if ($a->argc == 1) {
215
216                 // List messages
217
218                 $o .= $header;
219
220                 $total = 0;
221                 $r = q("SELECT count(*) AS `total`, ANY_VALUE(`created`) AS `created` FROM `mail`
222                         WHERE `mail`.`uid` = %d GROUP BY `parent-uri` ORDER BY `created` DESC",
223                         intval(local_user())
224                 );
225                 if (DBA::isResult($r)) {
226                         $total = $r[0]['total'];
227                 }
228
229                 $pager = new Pager(DI::l10n(), DI::args()->getQueryString());
230
231                 $r = get_messages(local_user(), $pager->getStart(), $pager->getItemsPerPage());
232
233                 if (!DBA::isResult($r)) {
234                         notice(DI::l10n()->t('No messages.'));
235                         return $o;
236                 }
237
238                 $o .= render_messages($r, 'mail_list.tpl');
239
240                 $o .= $pager->renderFull($total);
241
242                 return $o;
243         }
244
245         if (($a->argc > 1) && (intval($a->argv[1]))) {
246
247                 $o .= $header;
248
249                 $message = DBA::fetchFirst("
250                         SELECT `mail`.*, `contact`.`name`, `contact`.`url`, `contact`.`thumb`
251                         FROM `mail`
252                         LEFT JOIN `contact` ON `mail`.`contact-id` = `contact`.`id`
253                         WHERE `mail`.`uid` = ? AND `mail`.`id` = ?
254                         LIMIT 1",
255                         local_user(),
256                         $a->argv[1]
257                 );
258                 if (DBA::isResult($message)) {
259                         $contact_id = $message['contact-id'];
260
261                         $params = [
262                                 local_user(),
263                                 $message['parent-uri']
264                         ];
265
266                         if ($message['convid']) {
267                                 $sql_extra = "AND (`mail`.`parent-uri` = ? OR `mail`.`convid` = ?)";
268                                 $params[] = $message['convid'];
269                         } else {
270                                 $sql_extra = "AND `mail`.`parent-uri` = ?";
271                         }
272                         $messages_stmt = DBA::p("
273                                 SELECT `mail`.*, `contact`.`name`, `contact`.`url`, `contact`.`thumb`
274                                 FROM `mail`
275                                 LEFT JOIN `contact` ON `mail`.`contact-id` = `contact`.`id`
276                                 WHERE `mail`.`uid` = ?
277                                 $sql_extra
278                                 ORDER BY `mail`.`created` ASC",
279                                 ...$params
280                         );
281
282                         $messages = DBA::toArray($messages_stmt);
283
284                         DBA::update('mail', ['seen' => 1], ['parent-uri' => $message['parent-uri'], 'uid' => local_user()]);
285                         DBA::update('notify', ['seen' => 1], ['type' => Type::MAIL, 'parent' => $message['id'], 'uid' => local_user()]);
286                 } else {
287                         $messages = false;
288                 }
289
290                 if (!DBA::isResult($messages)) {
291                         notice(DI::l10n()->t('Message not available.'));
292                         return $o;
293                 }
294
295                 $tpl = Renderer::getMarkupTemplate('msg-header.tpl');
296                 DI::page()['htmlhead'] .= Renderer::replaceMacros($tpl, [
297                         '$baseurl' => DI::baseUrl()->get(true),
298                         '$nickname' => $a->user['nickname'],
299                         '$linkurl' => DI::l10n()->t('Please enter a link URL:')
300                 ]);
301
302                 $mails = [];
303                 $seen = 0;
304                 $unknown = false;
305
306                 foreach ($messages as $message) {
307                         if ($message['unknown']) {
308                                 $unknown = true;
309                         }
310
311                         if ($message['from-url'] == $myprofile) {
312                                 $from_url = $myprofile;
313                                 $sparkle = '';
314                         } else {
315                                 $from_url = Contact::magicLink($message['from-url']);
316                                 $sparkle = ' sparkle';
317                         }
318
319                         $extracted = item_extract_images($message['body']);
320                         if ($extracted['images']) {
321                                 $message['body'] = item_redir_and_replace_images($extracted['body'], $extracted['images'], $message['contact-id']);
322                         }
323
324                         $from_name_e = $message['from-name'];
325                         $subject_e = $message['title'];
326                         $body_e = BBCode::convert($message['body']);
327                         $to_name_e = $message['name'];
328
329                         $contact = Contact::getByURL($message['from-url'], false, ['thumb', 'addr', 'id', 'avatar']);
330                         $from_photo = Contact::getThumb($contact, $message['from-photo']);
331
332                         $mails[] = [
333                                 'id' => $message['id'],
334                                 'from_name' => $from_name_e,
335                                 'from_url' => $from_url,
336                                 'from_addr' => $contact['addr'],
337                                 'sparkle' => $sparkle,
338                                 'from_photo' => $from_photo,
339                                 'subject' => $subject_e,
340                                 'body' => $body_e,
341                                 'delete' => DI::l10n()->t('Delete message'),
342                                 'to_name' => $to_name_e,
343                                 'date' => DateTimeFormat::local($message['created'], DI::l10n()->t('D, d M Y - g:i A')),
344                                 'ago' => Temporal::getRelativeDate($message['created']),
345                         ];
346
347                         $seen = $message['seen'];
348                 }
349
350                 $select = $message['name'] . '<input type="hidden" name="recipient" value="' . $contact_id . '" />';
351                 $parent = '<input type="hidden" name="replyto" value="' . $message['parent-uri'] . '" />';
352
353                 $tpl = Renderer::getMarkupTemplate('mail_display.tpl');
354                 $o = Renderer::replaceMacros($tpl, [
355                         '$thread_id' => $a->argv[1],
356                         '$thread_subject' => $message['title'],
357                         '$thread_seen' => $seen,
358                         '$delete' => DI::l10n()->t('Delete conversation'),
359                         '$canreply' => (($unknown) ? false : '1'),
360                         '$unknown_text' => DI::l10n()->t("No secure communications available. You <strong>may</strong> be able to respond from the sender's profile page."),
361                         '$mails' => $mails,
362
363                         // reply
364                         '$header' => DI::l10n()->t('Send Reply'),
365                         '$to' => DI::l10n()->t('To:'),
366                         '$subject' => DI::l10n()->t('Subject:'),
367                         '$subjtxt' => $message['title'],
368                         '$readonly' => ' readonly="readonly" style="background: #BBBBBB;" ',
369                         '$yourmessage' => DI::l10n()->t('Your message:'),
370                         '$text' => '',
371                         '$select' => $select,
372                         '$parent' => $parent,
373                         '$upload' => DI::l10n()->t('Upload photo'),
374                         '$insert' => DI::l10n()->t('Insert web link'),
375                         '$submit' => DI::l10n()->t('Submit'),
376                         '$wait' => DI::l10n()->t('Please wait')
377                 ]);
378
379                 return $o;
380         }
381 }
382
383 /**
384  * @param int $uid
385  * @param int $start
386  * @param int $limit
387  * @return array
388  */
389 function get_messages($uid, $start, $limit)
390 {
391         return DBA::toArray(DBA::p('SELECT
392                         m.`id`,
393                         m.`uid`,
394                         m.`guid`,
395                         m.`from-name`,
396                         m.`from-photo`,
397                         m.`from-url`,
398                         m.`contact-id`,
399                         m.`convid`,
400                         m.`title`,
401                         m.`body`,
402                         m.`seen`,
403                         m.`reply`,
404                         m.`replied`,
405                         m.`unknown`,
406                         m.`uri`,
407                         m.`parent-uri`,
408                         m.`created`,
409                         c.`name`,
410                         c.`url`,
411                         c.`thumb`,
412                         c.`network`,
413                 m2.`count`,
414                 m2.`mailcreated`,
415                 m2.`mailseen`
416         FROM `mail` m
417         JOIN (
418                 SELECT
419                         `parent-uri`,
420                     MIN(`id`)      AS `id`,
421                     COUNT(*)       AS `count`,
422                     MAX(`created`) AS `mailcreated`,
423                     MIN(`seen`)    AS `mailseen`
424                 FROM `mail`
425                 WHERE `uid` = ?
426                 GROUP BY `parent-uri`
427         ) m2 ON m.`parent-uri` = m2.`parent-uri` AND m.`id` = m2.`id`
428                 LEFT JOIN `contact` c ON m.`contact-id` = c.`id`
429                 WHERE m.`uid` = ?
430                 ORDER BY m2.`mailcreated` DESC
431                 LIMIT ?, ?'
432                 , $uid, $uid, $start, $limit));
433 }
434
435 function render_messages(array $msg, $t)
436 {
437         $a = DI::app();
438
439         $tpl = Renderer::getMarkupTemplate($t);
440         $rslt = '';
441
442         $myprofile = DI::baseUrl() . '/profile/' . $a->user['nickname'];
443
444         foreach ($msg as $rr) {
445                 if ($rr['unknown']) {
446                         $participants = DI::l10n()->t("Unknown sender - %s", $rr['from-name']);
447                 } elseif (Strings::compareLink($rr['from-url'], $myprofile)) {
448                         $participants = DI::l10n()->t("You and %s", $rr['name']);
449                 } else {
450                         $participants = DI::l10n()->t("%s and You", $rr['from-name']);
451                 }
452
453                 $body_e = $rr['body'];
454                 $to_name_e = $rr['name'];
455
456                 $contact = Contact::getByURL($rr['url'], false, ['thumb', 'addr', 'id', 'avatar']);
457                 $from_photo = Contact::getThumb($contact, $rr['thumb'] ?: $rr['from-photo']);
458
459                 $rslt .= Renderer::replaceMacros($tpl, [
460                         '$id' => $rr['id'],
461                         '$from_name' => $participants,
462                         '$from_url' => Contact::magicLink($rr['url']),
463                         '$from_addr' => $contact['addr'] ?? '',
464                         '$sparkle' => ' sparkle',
465                         '$from_photo' => $from_photo,
466                         '$subject' => $rr['title'],
467                         '$delete' => DI::l10n()->t('Delete conversation'),
468                         '$body' => $body_e,
469                         '$to_name' => $to_name_e,
470                         '$date' => DateTimeFormat::local($rr['mailcreated'], DI::l10n()->t('D, d M Y - g:i A')),
471                         '$ago' => Temporal::getRelativeDate($rr['mailcreated']),
472                         '$seen' => $rr['mailseen'],
473                         '$count' => DI::l10n()->tt('%d message', '%d messages', $rr['count']),
474                 ]);
475         }
476
477         return $rslt;
478 }