]> git.mxchange.org Git - friendica.git/blob - mod/message.php
Some more "q" calls and deprecated logging replaced
[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                         $parentmail = DBA::selectFirst('mail', ['parent-uri'], ['id' => DI::args()->getArgv()[2], 'uid' => local_user()]);
162                         if (DBA::isResult($parentmail)) {
163                                 $parent = $parentmail['parent-uri'];
164
165                                 if (!DBA::delete('mail', ['parent-uri' => $parent, 'uid' => local_user()])) {
166                                         notice(DI::l10n()->t('Conversation was not removed.'));
167                                 }
168                         }
169                         DI::baseUrl()->redirect('message');
170                 }
171         }
172
173         if ((DI::args()->getArgc() > 1) && (DI::args()->getArgv()[1] === 'new')) {
174                 $o .= $header;
175
176                 $tpl = Renderer::getMarkupTemplate('msg-header.tpl');
177                 DI::page()['htmlhead'] .= Renderer::replaceMacros($tpl, [
178                         '$baseurl' => DI::baseUrl()->get(true),
179                         '$nickname' => $a->getLoggedInUserNickname(),
180                         '$linkurl' => DI::l10n()->t('Please enter a link URL:')
181                 ]);
182
183                 $recipientId = DI::args()->getArgv()[2] ?? null;
184
185                 $select = ACL::getMessageContactSelectHTML($recipientId);
186
187                 $tpl = Renderer::getMarkupTemplate('prv_message.tpl');
188                 $o .= Renderer::replaceMacros($tpl, [
189                         '$header'     => DI::l10n()->t('Send Private Message'),
190                         '$to'         => DI::l10n()->t('To:'),
191                         '$subject'    => DI::l10n()->t('Subject:'),
192                         '$subjtxt'    => $_REQUEST['subject'] ?? '',
193                         '$text'       => $_REQUEST['body'] ?? '',
194                         '$readonly'   => '',
195                         '$yourmessage'=> DI::l10n()->t('Your message:'),
196                         '$select'     => $select,
197                         '$parent'     => '',
198                         '$upload'     => DI::l10n()->t('Upload photo'),
199                         '$insert'     => DI::l10n()->t('Insert web link'),
200                         '$wait'       => DI::l10n()->t('Please wait'),
201                         '$submit'     => DI::l10n()->t('Submit')
202                 ]);
203                 return $o;
204         }
205
206
207         $_SESSION['return_path'] = DI::args()->getQueryString();
208
209         if (DI::args()->getArgc() == 1) {
210
211                 // List messages
212
213                 $o .= $header;
214
215                 $total = 0;
216                 $r = q("SELECT count(*) AS `total`, ANY_VALUE(`created`) AS `created` FROM `mail`
217                         WHERE `mail`.`uid` = %d GROUP BY `parent-uri` ORDER BY `created` DESC",
218                         intval(local_user())
219                 );
220                 if (DBA::isResult($r)) {
221                         $total = $r[0]['total'];
222                 }
223
224                 $pager = new Pager(DI::l10n(), DI::args()->getQueryString());
225
226                 $r = get_messages(local_user(), $pager->getStart(), $pager->getItemsPerPage());
227
228                 if (!DBA::isResult($r)) {
229                         notice(DI::l10n()->t('No messages.'));
230                         return $o;
231                 }
232
233                 $o .= render_messages($r, 'mail_list.tpl');
234
235                 $o .= $pager->renderFull($total);
236
237                 return $o;
238         }
239
240         if ((DI::args()->getArgc() > 1) && (intval(DI::args()->getArgv()[1]))) {
241
242                 $o .= $header;
243
244                 $message = DBA::fetchFirst("
245                         SELECT `mail`.*, `contact`.`name`, `contact`.`url`, `contact`.`thumb`
246                         FROM `mail`
247                         LEFT JOIN `contact` ON `mail`.`contact-id` = `contact`.`id`
248                         WHERE `mail`.`uid` = ? AND `mail`.`id` = ?
249                         LIMIT 1",
250                         local_user(),
251                         DI::args()->getArgv()[1]
252                 );
253                 if (DBA::isResult($message)) {
254                         $contact_id = $message['contact-id'];
255
256                         $params = [
257                                 local_user(),
258                                 $message['parent-uri']
259                         ];
260
261                         if ($message['convid']) {
262                                 $sql_extra = "AND (`mail`.`parent-uri` = ? OR `mail`.`convid` = ?)";
263                                 $params[] = $message['convid'];
264                         } else {
265                                 $sql_extra = "AND `mail`.`parent-uri` = ?";
266                         }
267                         $messages_stmt = DBA::p("
268                                 SELECT `mail`.*, `contact`.`name`, `contact`.`url`, `contact`.`thumb`
269                                 FROM `mail`
270                                 LEFT JOIN `contact` ON `mail`.`contact-id` = `contact`.`id`
271                                 WHERE `mail`.`uid` = ?
272                                 $sql_extra
273                                 ORDER BY `mail`.`created` ASC",
274                                 ...$params
275                         );
276
277                         $messages = DBA::toArray($messages_stmt);
278
279                         DBA::update('mail', ['seen' => 1], ['parent-uri' => $message['parent-uri'], 'uid' => local_user()]);
280                 } else {
281                         $messages = false;
282                 }
283
284                 if (!DBA::isResult($messages)) {
285                         notice(DI::l10n()->t('Message not available.'));
286                         return $o;
287                 }
288
289                 $tpl = Renderer::getMarkupTemplate('msg-header.tpl');
290                 DI::page()['htmlhead'] .= Renderer::replaceMacros($tpl, [
291                         '$baseurl' => DI::baseUrl()->get(true),
292                         '$nickname' => $a->getLoggedInUserNickname(),
293                         '$linkurl' => DI::l10n()->t('Please enter a link URL:')
294                 ]);
295
296                 $mails = [];
297                 $seen = 0;
298                 $unknown = false;
299
300                 foreach ($messages as $message) {
301                         if ($message['unknown']) {
302                                 $unknown = true;
303                         }
304
305                         if ($message['from-url'] == $myprofile) {
306                                 $from_url = $myprofile;
307                                 $sparkle = '';
308                         } else {
309                                 $from_url = Contact::magicLink($message['from-url']);
310                                 $sparkle = ' sparkle';
311                         }
312
313                         $from_name_e = $message['from-name'];
314                         $subject_e = $message['title'];
315                         $body_e = BBCode::convertForUriId($message['uri-id'], $message['body']);
316                         $to_name_e = $message['name'];
317
318                         $contact = Contact::getByURL($message['from-url'], false, ['thumb', 'addr', 'id', 'avatar']);
319                         $from_photo = Contact::getThumb($contact);
320
321                         $mails[] = [
322                                 'id' => $message['id'],
323                                 'from_name' => $from_name_e,
324                                 'from_url' => $from_url,
325                                 'from_addr' => $contact['addr'] ?? $from_url,
326                                 'sparkle' => $sparkle,
327                                 'from_photo' => $from_photo,
328                                 'subject' => $subject_e,
329                                 'body' => $body_e,
330                                 'delete' => DI::l10n()->t('Delete message'),
331                                 'to_name' => $to_name_e,
332                                 'date' => DateTimeFormat::local($message['created'], DI::l10n()->t('D, d M Y - g:i A')),
333                                 'ago' => Temporal::getRelativeDate($message['created']),
334                         ];
335
336                         $seen = $message['seen'];
337                 }
338
339                 $select = $message['name'] . '<input type="hidden" name="recipient" value="' . $contact_id . '" />';
340                 $parent = '<input type="hidden" name="replyto" value="' . $message['parent-uri'] . '" />';
341
342                 $tpl = Renderer::getMarkupTemplate('mail_display.tpl');
343                 $o = Renderer::replaceMacros($tpl, [
344                         '$thread_id' => DI::args()->getArgv()[1],
345                         '$thread_subject' => $message['title'],
346                         '$thread_seen' => $seen,
347                         '$delete' => DI::l10n()->t('Delete conversation'),
348                         '$canreply' => (($unknown) ? false : '1'),
349                         '$unknown_text' => DI::l10n()->t("No secure communications available. You <strong>may</strong> be able to respond from the sender's profile page."),
350                         '$mails' => $mails,
351
352                         // reply
353                         '$header' => DI::l10n()->t('Send Reply'),
354                         '$to' => DI::l10n()->t('To:'),
355                         '$subject' => DI::l10n()->t('Subject:'),
356                         '$subjtxt' => $message['title'],
357                         '$readonly' => ' readonly="readonly" style="background: #BBBBBB;" ',
358                         '$yourmessage' => DI::l10n()->t('Your message:'),
359                         '$text' => '',
360                         '$select' => $select,
361                         '$parent' => $parent,
362                         '$upload' => DI::l10n()->t('Upload photo'),
363                         '$insert' => DI::l10n()->t('Insert web link'),
364                         '$submit' => DI::l10n()->t('Submit'),
365                         '$wait' => DI::l10n()->t('Please wait')
366                 ]);
367
368                 return $o;
369         }
370 }
371
372 /**
373  * @param int $uid
374  * @param int $start
375  * @param int $limit
376  * @return array
377  */
378 function get_messages(int $uid, int $start, int $limit)
379 {
380         return DBA::toArray(DBA::p('SELECT
381                         m.`id`,
382                         m.`uid`,
383                         m.`guid`,
384                         m.`from-name`,
385                         m.`from-photo`,
386                         m.`from-url`,
387                         m.`contact-id`,
388                         m.`convid`,
389                         m.`title`,
390                         m.`body`,
391                         m.`seen`,
392                         m.`reply`,
393                         m.`replied`,
394                         m.`unknown`,
395                         m.`uri`,
396                         m.`parent-uri`,
397                         m.`created`,
398                         c.`name`,
399                         c.`url`,
400                         c.`thumb`,
401                         c.`network`,
402                 m2.`count`,
403                 m2.`mailcreated`,
404                 m2.`mailseen`
405         FROM `mail` m
406         JOIN (
407                 SELECT
408                         `parent-uri`,
409                     MIN(`id`)      AS `id`,
410                     COUNT(*)       AS `count`,
411                     MAX(`created`) AS `mailcreated`,
412                     MIN(`seen`)    AS `mailseen`
413                 FROM `mail`
414                 WHERE `uid` = ?
415                 GROUP BY `parent-uri`
416         ) m2 ON m.`parent-uri` = m2.`parent-uri` AND m.`id` = m2.`id`
417                 LEFT JOIN `contact` c ON m.`contact-id` = c.`id`
418                 WHERE m.`uid` = ?
419                 ORDER BY m2.`mailcreated` DESC
420                 LIMIT ?, ?'
421                 , $uid, $uid, $start, $limit));
422 }
423
424 function render_messages(array $msg, $t)
425 {
426         $a = DI::app();
427
428         $tpl = Renderer::getMarkupTemplate($t);
429         $rslt = '';
430
431         $myprofile = DI::baseUrl() . '/profile/' . $a->getLoggedInUserNickname();
432
433         foreach ($msg as $rr) {
434                 if ($rr['unknown']) {
435                         $participants = DI::l10n()->t("Unknown sender - %s", $rr['from-name']);
436                 } elseif (Strings::compareLink($rr['from-url'], $myprofile)) {
437                         $participants = DI::l10n()->t("You and %s", $rr['name']);
438                 } else {
439                         $participants = DI::l10n()->t("%s and You", $rr['from-name']);
440                 }
441
442                 $body_e = $rr['body'];
443                 $to_name_e = $rr['name'];
444
445                 if (is_null($rr['url'])) {
446                         // contact-id is pointing to a non existing contact
447                         continue;
448                 }
449
450                 $contact = Contact::getByURL($rr['url'], false, ['thumb', 'addr', 'id', 'avatar']);
451                 $from_photo = Contact::getThumb($contact);
452
453                 $rslt .= Renderer::replaceMacros($tpl, [
454                         '$id' => $rr['id'],
455                         '$from_name' => $participants,
456                         '$from_url' => Contact::magicLink($rr['url']),
457                         '$from_addr' => $contact['addr'] ?? '',
458                         '$sparkle' => ' sparkle',
459                         '$from_photo' => $from_photo,
460                         '$subject' => $rr['title'],
461                         '$delete' => DI::l10n()->t('Delete conversation'),
462                         '$body' => $body_e,
463                         '$to_name' => $to_name_e,
464                         '$date' => DateTimeFormat::local($rr['mailcreated'], DI::l10n()->t('D, d M Y - g:i A')),
465                         '$ago' => Temporal::getRelativeDate($rr['mailcreated']),
466                         '$seen' => $rr['mailseen'],
467                         '$count' => DI::l10n()->tt('%d message', '%d messages', $rr['count']),
468                 ]);
469         }
470
471         return $rslt;
472 }