]> git.mxchange.org Git - friendica.git/blob - mod/message.php
App::get_baseurl is now replaced with System::baseUrl
[friendica.git] / mod / message.php
1 <?php
2
3 use Friendica\App;
4 use Friendica\Core\System;
5
6 require_once('include/acl_selectors.php');
7 require_once('include/message.php');
8 require_once('include/Smilies.php');
9
10 function message_init(App $a) {
11
12         $tabs = '';
13
14         if ($a->argc >1 && is_numeric($a->argv[1])) {
15                 $tabs = render_messages(get_messages(local_user(),0,5), 'mail_list.tpl');
16         }
17
18         $new = array(
19                 'label' => t('New Message'),
20                 'url' => 'message/new',
21                 'sel'=> ($a->argv[1] == 'new'),
22                 'accesskey' => 'm',
23         );
24
25         $tpl = get_markup_template('message_side.tpl');
26         $a->page['aside'] = replace_macros($tpl, array(
27                 '$tabs'=>$tabs,
28                 '$new'=>$new,
29         ));
30         $base = System::baseUrl();
31
32         $head_tpl = get_markup_template('message-head.tpl');
33         $a->page['htmlhead'] .= replace_macros($head_tpl,array(
34                 '$baseurl' => System::baseUrl(true),
35                 '$base' => $base
36         ));
37
38         $end_tpl = get_markup_template('message-end.tpl');
39         $a->page['end'] .= replace_macros($end_tpl,array(
40                 '$baseurl' => System::baseUrl(true),
41                 '$base' => $base
42         ));
43
44 }
45
46 function message_post(App $a) {
47
48         if (! local_user()) {
49                 notice( t('Permission denied.') . EOL);
50                 return;
51         }
52
53         $replyto   = ((x($_REQUEST,'replyto'))   ? notags(trim($_REQUEST['replyto']))   : '');
54         $subject   = ((x($_REQUEST,'subject'))   ? notags(trim($_REQUEST['subject']))   : '');
55         $body      = ((x($_REQUEST,'body'))      ? escape_tags(trim($_REQUEST['body'])) : '');
56         $recipient = ((x($_REQUEST,'messageto')) ? intval($_REQUEST['messageto'])       : 0 );
57
58         $ret = send_message($recipient, $body, $subject, $replyto);
59         $norecip = false;
60
61         switch($ret){
62                 case -1:
63                         notice( t('No recipient selected.') . EOL );
64                         $norecip = true;
65                         break;
66                 case -2:
67                         notice( t('Unable to locate contact information.') . EOL );
68                         break;
69                 case -3:
70                         notice( t('Message could not be sent.') . EOL );
71                         break;
72                 case -4:
73                         notice( t('Message collection failure.') . EOL );
74                         break;
75                 default:
76                         info( t('Message sent.') . EOL );
77         }
78
79         // fake it to go back to the input form if no recipient listed
80
81         if($norecip) {
82                 $a->argc = 2;
83                 $a->argv[1] = 'new';
84         }
85         else
86                 goaway($_SESSION['return_url']);
87
88 }
89
90 // Note: the code in 'item_extract_images' and 'item_redir_and_replace_images'
91 // is identical to the code in include/conversation.php
92 if(! function_exists('item_extract_images')) {
93 function item_extract_images($body) {
94
95         $saved_image = array();
96         $orig_body = $body;
97         $new_body = '';
98
99         $cnt = 0;
100         $img_start = strpos($orig_body, '[img');
101         $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
102         $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
103         while(($img_st_close !== false) && ($img_end !== false)) {
104
105                 $img_st_close++; // make it point to AFTER the closing bracket
106                 $img_end += $img_start;
107
108                 if(! strcmp(substr($orig_body, $img_start + $img_st_close, 5), 'data:')) {
109                         // This is an embedded image
110
111                         $saved_image[$cnt] = substr($orig_body, $img_start + $img_st_close, $img_end - ($img_start + $img_st_close));
112                         $new_body = $new_body . substr($orig_body, 0, $img_start) . '[!#saved_image' . $cnt . '#!]';
113
114                         $cnt++;
115                 }
116                 else
117                         $new_body = $new_body . substr($orig_body, 0, $img_end + strlen('[/img]'));
118
119                 $orig_body = substr($orig_body, $img_end + strlen('[/img]'));
120
121                 if($orig_body === false) // in case the body ends on a closing image tag
122                         $orig_body = '';
123
124                 $img_start = strpos($orig_body, '[img');
125                 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
126                 $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
127         }
128
129         $new_body = $new_body . $orig_body;
130
131         return array('body' => $new_body, 'images' => $saved_image);
132 }}
133
134 if(! function_exists('item_redir_and_replace_images')) {
135 function item_redir_and_replace_images($body, $images, $cid) {
136
137         $origbody = $body;
138         $newbody = '';
139
140         for($i = 0; $i < count($images); $i++) {
141                 $search = '/\[url\=(.*?)\]\[!#saved_image' . $i . '#!\]\[\/url\]' . '/is';
142                 $replace = '[url=' . System::baseUrl() . '/redir/' . $cid
143                            . '?f=1&url=' . '$1' . '][!#saved_image' . $i . '#!][/url]' ;
144
145                 $img_end = strpos($origbody, '[!#saved_image' . $i . '#!][/url]') + strlen('[!#saved_image' . $i . '#!][/url]');
146                 $process_part = substr($origbody, 0, $img_end);
147                 $origbody = substr($origbody, $img_end);
148
149                 $process_part = preg_replace($search, $replace, $process_part);
150                 $newbody = $newbody . $process_part;
151         }
152         $newbody = $newbody . $origbody;
153
154         $cnt = 0;
155         foreach ($images as $image) {
156                 // We're depending on the property of 'foreach' (specified on the PHP website) that
157                 // it loops over the array starting from the first element and going sequentially
158                 // to the last element
159                 $newbody = str_replace('[!#saved_image' . $cnt . '#!]', '[img]' . $image . '[/img]', $newbody);
160                 $cnt++;
161         }
162
163         return $newbody;
164 }}
165
166
167
168 function message_content(App $a) {
169
170         $o = '';
171         nav_set_selected('messages');
172
173         if (! local_user()) {
174                 notice( t('Permission denied.') . EOL);
175                 return;
176         }
177
178         $myprofile = System::baseUrl().'/profile/' . $a->user['nickname'];
179
180         $tpl = get_markup_template('mail_head.tpl');
181         $header = replace_macros($tpl, array(
182                 '$messages' => t('Messages'),
183                 '$tab_content' => $tab_content
184         ));
185
186
187         if(($a->argc == 3) && ($a->argv[1] === 'drop' || $a->argv[1] === 'dropconv')) {
188                 if(! intval($a->argv[2]))
189                         return;
190
191                 // Check if we should do HTML-based delete confirmation
192                 if($_REQUEST['confirm']) {
193                         // <form> can't take arguments in its "action" parameter
194                         // so add any arguments as hidden inputs
195                         $query = explode_querystring($a->query_string);
196                         $inputs = array();
197                         foreach($query['args'] as $arg) {
198                                 if(strpos($arg, 'confirm=') === false) {
199                                         $arg_parts = explode('=', $arg);
200                                         $inputs[] = array('name' => $arg_parts[0], 'value' => $arg_parts[1]);
201                                 }
202                         }
203
204                         //$a->page['aside'] = '';
205                         return replace_macros(get_markup_template('confirm.tpl'), array(
206                                 '$method' => 'get',
207                                 '$message' => t('Do you really want to delete this message?'),
208                                 '$extra_inputs' => $inputs,
209                                 '$confirm' => t('Yes'),
210                                 '$confirm_url' => $query['base'],
211                                 '$confirm_name' => 'confirmed',
212                                 '$cancel' => t('Cancel'),
213                         ));
214                 }
215                 // Now check how the user responded to the confirmation query
216                 if($_REQUEST['canceled']) {
217                         goaway($_SESSION['return_url']);
218                 }
219
220                 $cmd = $a->argv[1];
221                 if($cmd === 'drop') {
222                         $r = q("DELETE FROM `mail` WHERE `id` = %d AND `uid` = %d LIMIT 1",
223                                 intval($a->argv[2]),
224                                 intval(local_user())
225                         );
226                         if ($r) {
227                                 info( t('Message deleted.') . EOL );
228                         }
229                         //goaway(System::baseUrl(true) . '/message' );
230                         goaway($_SESSION['return_url']);
231                 }
232                 else {
233                         $r = q("SELECT `parent-uri`,`convid` FROM `mail` WHERE `id` = %d AND `uid` = %d LIMIT 1",
234                                 intval($a->argv[2]),
235                                 intval(local_user())
236                         );
237                         if (dbm::is_result($r)) {
238                                 $parent = $r[0]['parent-uri'];
239                                 $convid = $r[0]['convid'];
240
241                                 $r = q("DELETE FROM `mail` WHERE `parent-uri` = '%s' AND `uid` = %d ",
242                                         dbesc($parent),
243                                         intval(local_user())
244                                 );
245
246                                 // remove diaspora conversation pointer
247                                 // Actually if we do this, we can never receive another reply to that conversation,
248                                 // as we will never again have the info we need to re-create it.
249                                 // We'll just have to orphan it.
250
251                                 //if($convid) {
252                                 //      q("delete from conv where id = %d limit 1",
253                                 //              intval($convid)
254                                 //      );
255                                 //}
256
257                                 if($r)
258                                         info( t('Conversation removed.') . EOL );
259                         }
260                         //goaway(System::baseUrl(true) . '/message' );
261                         goaway($_SESSION['return_url']);
262                 }
263
264         }
265
266         if(($a->argc > 1) && ($a->argv[1] === 'new')) {
267
268                 $o .= $header;
269
270                 $tpl = get_markup_template('msg-header.tpl');
271                 $a->page['htmlhead'] .= replace_macros($tpl, array(
272                         '$baseurl' => System::baseUrl(true),
273                         '$nickname' => $a->user['nickname'],
274                         '$linkurl' => t('Please enter a link URL:')
275                 ));
276
277                 $tpl = get_markup_template('msg-end.tpl');
278                 $a->page['end'] .= replace_macros($tpl, array(
279                         '$baseurl' => System::baseUrl(true),
280                         '$nickname' => $a->user['nickname'],
281                         '$linkurl' => t('Please enter a link URL:')
282                 ));
283
284                 $preselect = (isset($a->argv[2])?array($a->argv[2]):false);
285
286
287                 $prename = $preurl = $preid = '';
288
289                 if($preselect) {
290                         $r = q("SELECT `name`, `url`, `id` FROM `contact` WHERE `uid` = %d AND `id` = %d LIMIT 1",
291                                 intval(local_user()),
292                                 intval($a->argv[2])
293                         );
294                         if (!dbm::is_result($r)) {
295                                 $r = q("SELECT `name`, `url`, `id` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' LIMIT 1",
296                                         intval(local_user()),
297                                         dbesc(normalise_link(base64_decode($a->argv[2])))
298                                 );
299                         }
300
301                         if (!dbm::is_result($r)) {
302                                 $r = q("SELECT `name`, `url`, `id` FROM `contact` WHERE `uid` = %d AND `addr` = '%s' LIMIT 1",
303                                         intval(local_user()),
304                                         dbesc(base64_decode($a->argv[2]))
305                                 );
306                         }
307
308                         if (dbm::is_result($r)) {
309                                 $prename = $r[0]['name'];
310                                 $preurl = $r[0]['url'];
311                                 $preid = $r[0]['id'];
312                                 $preselect = array($preid);
313                         } else
314                                 $preselect = false;
315                 }
316
317                 $prefill = (($preselect) ? $prename  : '');
318
319                 // the ugly select box
320
321                 $select = contact_select('messageto','message-to-select', $preselect, 4, true, false, false, 10);
322
323                 $tpl = get_markup_template('prv_message.tpl');
324                 $o .= replace_macros($tpl,array(
325                         '$header' => t('Send Private Message'),
326                         '$to' => t('To:'),
327                         '$showinputs' => 'true',
328                         '$prefill' => $prefill,
329                         '$autocomp' => $autocomp,
330                         '$preid' => $preid,
331                         '$subject' => t('Subject:'),
332                         '$subjtxt' => ((x($_REQUEST,'subject')) ? strip_tags($_REQUEST['subject']) : ''),
333                         '$text' => ((x($_REQUEST,'body')) ? escape_tags(htmlspecialchars($_REQUEST['body'])) : ''),
334                         '$readonly' => '',
335                         '$yourmessage' => t('Your message:'),
336                         '$select' => $select,
337                         '$parent' => '',
338                         '$upload' => t('Upload photo'),
339                         '$insert' => t('Insert web link'),
340                         '$wait' => t('Please wait'),
341                         '$submit' => t('Submit')
342                 ));
343                 return $o;
344         }
345
346
347         $_SESSION['return_url'] = $a->query_string;
348
349         if ($a->argc == 1) {
350
351                 // List messages
352
353                 $o .= $header;
354
355                 $r = q("SELECT count(*) AS `total`, ANY_VALUE(`created`) AS `created` FROM `mail`
356                         WHERE `mail`.`uid` = %d GROUP BY `parent-uri` ORDER BY `created` DESC",
357                         intval(local_user())
358                 );
359
360                 if (dbm::is_result($r)) {
361                         $a->set_pager_total($r[0]['total']);
362                 }
363
364                 $r = get_messages(local_user(), $a->pager['start'], $a->pager['itemspage']);
365
366                 if (! dbm::is_result($r)) {
367                         info( t('No messages.') . EOL);
368                         return $o;
369                 }
370
371                 $o .= render_messages($r, 'mail_list.tpl');
372
373                 $o .= paginate($a);
374
375                 return $o;
376         }
377
378         if(($a->argc > 1) && (intval($a->argv[1]))) {
379
380                 $o .= $header;
381
382                 $r = q("SELECT `mail`.*, `contact`.`name`, `contact`.`url`, `contact`.`thumb`
383                         FROM `mail` LEFT JOIN `contact` ON `mail`.`contact-id` = `contact`.`id`
384                         WHERE `mail`.`uid` = %d AND `mail`.`id` = %d LIMIT 1",
385                         intval(local_user()),
386                         intval($a->argv[1])
387                 );
388                 if (dbm::is_result($r)) {
389                         $contact_id = $r[0]['contact-id'];
390                         $convid = $r[0]['convid'];
391
392                         $sql_extra = sprintf(" and `mail`.`parent-uri` = '%s' ", dbesc($r[0]['parent-uri']));
393                         if($convid)
394                                 $sql_extra = sprintf(" and ( `mail`.`parent-uri` = '%s' OR `mail`.`convid` = '%d' ) ",
395                                         dbesc($r[0]['parent-uri']),
396                                         intval($convid)
397                                 );
398
399                         $messages = q("SELECT `mail`.*, `contact`.`name`, `contact`.`url`, `contact`.`thumb`
400                                 FROM `mail` LEFT JOIN `contact` ON `mail`.`contact-id` = `contact`.`id`
401                                 WHERE `mail`.`uid` = %d $sql_extra ORDER BY `mail`.`created` ASC",
402                                 intval(local_user())
403                         );
404                 }
405                 if(! count($messages)) {
406                         notice( t('Message not available.') . EOL );
407                         return $o;
408                 }
409
410                 $r = q("UPDATE `mail` SET `seen` = 1 WHERE `parent-uri` = '%s' AND `uid` = %d",
411                         dbesc($r[0]['parent-uri']),
412                         intval(local_user())
413                 );
414
415                 require_once("include/bbcode.php");
416
417                 $tpl = get_markup_template('msg-header.tpl');
418                 $a->page['htmlhead'] .= replace_macros($tpl, array(
419                         '$baseurl' => System::baseUrl(true),
420                         '$nickname' => $a->user['nickname'],
421                         '$linkurl' => t('Please enter a link URL:')
422                 ));
423
424                 $tpl = get_markup_template('msg-end.tpl');
425                 $a->page['end'] .= replace_macros($tpl, array(
426                         '$baseurl' => System::baseUrl(true),
427                         '$nickname' => $a->user['nickname'],
428                         '$linkurl' => t('Please enter a link URL:')
429                 ));
430
431                 $mails = array();
432                 $seen = 0;
433                 $unknown = false;
434
435                 foreach($messages as $message) {
436                         if($message['unknown'])
437                                 $unknown = true;
438                         if($message['from-url'] == $myprofile) {
439                                 $from_url = $myprofile;
440                                 $sparkle = '';
441                         } elseif ($message['contact-id'] != 0) {
442                                 $from_url = 'redir/'.$message['contact-id'];
443                                 $sparkle = ' sparkle';
444                         } else {
445                                 $from_url = $message['from-url']."?zrl=".urlencode($myprofile);
446                                 $sparkle = ' sparkle';
447                         }
448
449
450                         $extracted = item_extract_images($message['body']);
451                         if($extracted['images'])
452                                 $message['body'] = item_redir_and_replace_images($extracted['body'], $extracted['images'], $message['contact-id']);
453
454                         if($a->theme['template_engine'] === 'internal') {
455                                 $from_name_e = template_escape($message['from-name']);
456                                 $subject_e = template_escape($message['title']);
457                                 $body_e = template_escape(Smilies::replace(bbcode($message['body'])));
458                                 $to_name_e = template_escape($message['name']);
459                         } else {
460                                 $from_name_e = $message['from-name'];
461                                 $subject_e = $message['title'];
462                                 $body_e = Smilies::replace(bbcode($message['body']));
463                                 $to_name_e = $message['name'];
464                         }
465
466                         $contact = get_contact_details_by_url($message['from-url']);
467                         if (isset($contact["thumb"]))
468                                 $from_photo = $contact["thumb"];
469                         else
470                                 $from_photo = $message['from-photo'];
471
472                         $mails[] = array(
473                                 'id' => $message['id'],
474                                 'from_name' => $from_name_e,
475                                 'from_url' => $from_url,
476                                 'sparkle' => $sparkle,
477                                 'from_photo' => proxy_url($from_photo, false, PROXY_SIZE_THUMB),
478                                 'subject' => $subject_e,
479                                 'body' => $body_e,
480                                 'delete' => t('Delete message'),
481                                 'to_name' => $to_name_e,
482                                 'date' => datetime_convert('UTC',date_default_timezone_get(),$message['created'],'D, d M Y - g:i A'),
483                                 'ago' => relative_date($message['created']),
484                         );
485
486                         $seen = $message['seen'];
487                 }
488
489
490                 $select = $message['name'] . '<input type="hidden" name="messageto" value="' . $contact_id . '" />';
491                 $parent = '<input type="hidden" name="replyto" value="' . $message['parent-uri'] . '" />';
492
493                 $tpl = get_markup_template('mail_display.tpl');
494
495                 if($a->theme['template_engine'] === 'internal') {
496                         $subjtxt_e = template_escape($message['title']);
497                 }
498                 else {
499                         $subjtxt_e = $message['title'];
500                 }
501
502                 $o = replace_macros($tpl, array(
503                         '$thread_id' => $a->argv[1],
504                         '$thread_subject' => $message['title'],
505                         '$thread_seen' => $seen,
506                         '$delete' =>  t('Delete conversation'),
507                         '$canreply' => (($unknown) ? false : '1'),
508                         '$unknown_text' => t("No secure communications available. You <strong>may</strong> be able to respond from the sender's profile page."),
509                         '$mails' => $mails,
510
511                         // reply
512                         '$header' => t('Send Reply'),
513                         '$to' => t('To:'),
514                         '$showinputs' => '',
515                         '$subject' => t('Subject:'),
516                         '$subjtxt' => $subjtxt_e,
517                         '$readonly' => ' readonly="readonly" style="background: #BBBBBB;" ',
518                         '$yourmessage' => t('Your message:'),
519                         '$text' => '',
520                         '$select' => $select,
521                         '$parent' => $parent,
522                         '$upload' => t('Upload photo'),
523                         '$insert' => t('Insert web link'),
524                         '$submit' => t('Submit'),
525                         '$wait' => t('Please wait')
526
527                 ));
528
529                 return $o;
530         }
531 }
532
533 function get_messages($user, $lstart, $lend) {
534         //TODO: rewritte with a sub-query to get the first message of each private thread with certainty
535         return q("SELECT max(`mail`.`created`) AS `mailcreated`, min(`mail`.`seen`) AS `mailseen`,
536                 ANY_VALUE(`mail`.`id`) AS `id`, ANY_VALUE(`mail`.`uid`) AS `uid`, ANY_VALUE(`mail`.`guid`) AS `guid`,
537                 ANY_VALUE(`mail`.`from-name`) AS `from-name`, ANY_VALUE(`mail`.`from-photo`) AS `from-photo`,
538                 ANY_VALUE(`mail`.`from-url`) AS `from-url`, ANY_VALUE(`mail`.`contact-id`) AS `contact-id`,
539                 ANY_VALUE(`mail`.`convid`) AS `convid`, ANY_VALUE(`mail`.`title`) AS `title`, ANY_VALUE(`mail`.`body`) AS `body`,
540                 ANY_VALUE(`mail`.`seen`) AS `seen`, ANY_VALUE(`mail`.`reply`) AS `reply`, ANY_VALUE(`mail`.`replied`) AS `replied`,
541                 ANY_VALUE(`mail`.`unknown`) AS `unknown`, ANY_VALUE(`mail`.`uri`) AS `uri`,
542                 `mail`.`parent-uri`,
543                 ANY_VALUE(`mail`.`created`) AS `created`, ANY_VALUE(`contact`.`name`) AS `name`, ANY_VALUE(`contact`.`url`) AS `url`,
544                 ANY_VALUE(`contact`.`thumb`) AS `thumb`, ANY_VALUE(`contact`.`network`) AS `network`,
545                 count( * ) as `count`
546                 FROM `mail` LEFT JOIN `contact` ON `mail`.`contact-id` = `contact`.`id`
547                 WHERE `mail`.`uid` = %d GROUP BY `parent-uri` ORDER BY `mailcreated` DESC LIMIT %d , %d ",
548                 intval($user), intval($lstart), intval($lend)
549         );
550 }
551
552 function render_messages(array $msg, $t) {
553
554         $a = get_app();
555
556         $tpl = get_markup_template($t);
557         $rslt = '';
558
559         $myprofile = System::baseUrl().'/profile/' . $a->user['nickname'];
560
561         foreach($msg as $rr) {
562
563                 if($rr['unknown'])
564                         $participants = sprintf( t("Unknown sender - %s"),$rr['from-name']);
565                 elseif (link_compare($rr['from-url'], $myprofile))
566                         $participants = sprintf( t("You and %s"), $rr['name']);
567                 else
568                         $participants = sprintf(t("%s and You"), $rr['from-name']);
569
570                 if($a->theme['template_engine'] === 'internal') {
571                         $subject_e = template_escape((($rr['mailseen']) ? $rr['title'] : '<strong>' . $rr['title'] . '</strong>'));
572                         $body_e = template_escape($rr['body']);
573                         $to_name_e = template_escape($rr['name']);
574                 }
575                 else {
576                         $subject_e = (($rr['mailseen']) ? $rr['title'] : '<strong>' . $rr['title'] . '</strong>');
577                         $body_e = $rr['body'];
578                         $to_name_e = $rr['name'];
579                 }
580
581                 $contact = get_contact_details_by_url($rr['url']);
582                 if (isset($contact["thumb"]))
583                         $from_photo = $contact["thumb"];
584                 else
585                         $from_photo = (($rr['thumb']) ? $rr['thumb'] : $rr['from-photo']);
586
587                 $rslt .= replace_macros($tpl, array(
588                         '$id' => $rr['id'],
589                         '$from_name' => $participants,
590                         '$from_url' => (($rr['network'] === NETWORK_DFRN) ? 'redir/' . $rr['contact-id'] : $rr['url']),
591                         '$sparkle' => ' sparkle',
592                         '$from_photo' => proxy_url($from_photo, false, PROXY_SIZE_THUMB),
593                         '$subject' => $subject_e,
594                         '$delete' => t('Delete conversation'),
595                         '$body' => $body_e,
596                         '$to_name' => $to_name_e,
597                         '$date' => datetime_convert('UTC',date_default_timezone_get(),$rr['mailcreated'], t('D, d M Y - g:i A')),
598                                                                                                                         '$ago' => relative_date($rr['mailcreated']),
599                         '$seen' => $rr['mailseen'],
600                         '$count' => sprintf( tt('%d message', '%d messages', $rr['count']), $rr['count']),
601                 ));
602         }
603
604         return $rslt;
605 }