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