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