]> git.mxchange.org Git - friendica.git/blob - mod/message.php
Preview last five conversations in message-sidebar
[friendica.git] / mod / message.php
1 <?php
2
3 require_once('include/acl_selectors.php');
4 require_once('include/message.php');
5
6 function message_init(&$a) {
7
8         $tabs = '';
9
10         if (is_numeric($a->argv[1]))
11          $tabs = render_messages(get_messages(local_user(),0,5), 'mail_list.tpl');
12
13         $new = array(
14                 'label' => t('New Message'),
15                 'url' => $a->get_baseurl(true) . '/message/new',
16                 'sel'=> ($a->argv[1] == 'new'),
17                 'accesskey' => 'm',
18         );
19
20         $tpl = get_markup_template('message_side.tpl');
21         $a->page['aside'] = replace_macros($tpl, array(
22                 '$tabs'=>$tabs,
23                 '$new'=>$new,
24         ));
25         $base = $a->get_baseurl();
26
27         $head_tpl = get_markup_template('message-head.tpl');
28         $a->page['htmlhead'] .= replace_macros($head_tpl,array(
29                 '$baseurl' => $a->get_baseurl(true),
30                 '$base' => $base
31         ));
32
33         $end_tpl = get_markup_template('message-end.tpl');
34         $a->page['end'] .= replace_macros($end_tpl,array(
35                 '$baseurl' => $a->get_baseurl(true),
36                 '$base' => $base
37         ));
38
39 }
40
41 function message_post(&$a) {
42
43         if(! local_user()) {
44                 notice( t('Permission denied.') . EOL);
45                 return;
46         }
47
48         $replyto   = ((x($_REQUEST,'replyto'))   ? notags(trim($_REQUEST['replyto']))   : '');
49         $subject   = ((x($_REQUEST,'subject'))   ? notags(trim($_REQUEST['subject']))   : '');
50         $body      = ((x($_REQUEST,'body'))      ? escape_tags(trim($_REQUEST['body'])) : '');
51         $recipient = ((x($_REQUEST,'messageto')) ? intval($_REQUEST['messageto'])       : 0 );
52
53         // Work around doubled linefeeds in Tinymce 3.5b2
54
55 /*      $plaintext = intval(get_pconfig(local_user(),'system','plaintext') && !feature_enabled(local_user(),'richtext'));
56         if(! $plaintext) {
57                 $body = fix_mce_lf($body);
58         }*/
59         $plaintext = intval(!feature_enabled(local_user(),'richtext'));
60         if(! $plaintext) {
61                 $body = fix_mce_lf($body);
62         }
63
64         $ret = send_message($recipient, $body, $subject, $replyto);
65         $norecip = false;
66
67         switch($ret){
68                 case -1:
69                         notice( t('No recipient selected.') . EOL );
70                         $norecip = true;
71                         break;
72                 case -2:
73                         notice( t('Unable to locate contact information.') . EOL );
74                         break;
75                 case -3:
76                         notice( t('Message could not be sent.') . EOL );
77                         break;
78                 case -4:
79                         notice( t('Message collection failure.') . EOL );
80                         break;
81                 default:
82                         info( t('Message sent.') . EOL );
83         }
84
85         // fake it to go back to the input form if no recipient listed
86
87         if($norecip) {
88                 $a->argc = 2;
89                 $a->argv[1] = 'new';
90         }
91         else
92                 goaway($a->get_baseurl(true) . '/' . $_SESSION['return_url']);
93
94 }
95
96 // Note: the code in 'item_extract_images' and 'item_redir_and_replace_images'
97 // is identical to the code in include/conversation.php
98 if(! function_exists('item_extract_images')) {
99 function item_extract_images($body) {
100
101         $saved_image = array();
102         $orig_body = $body;
103         $new_body = '';
104
105         $cnt = 0;
106         $img_start = strpos($orig_body, '[img');
107         $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
108         $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
109         while(($img_st_close !== false) && ($img_end !== false)) {
110
111                 $img_st_close++; // make it point to AFTER the closing bracket
112                 $img_end += $img_start;
113
114                 if(! strcmp(substr($orig_body, $img_start + $img_st_close, 5), 'data:')) {
115                         // This is an embedded image
116
117                         $saved_image[$cnt] = substr($orig_body, $img_start + $img_st_close, $img_end - ($img_start + $img_st_close));
118                         $new_body = $new_body . substr($orig_body, 0, $img_start) . '[!#saved_image' . $cnt . '#!]';
119
120                         $cnt++;
121                 }
122                 else
123                         $new_body = $new_body . substr($orig_body, 0, $img_end + strlen('[/img]'));
124
125                 $orig_body = substr($orig_body, $img_end + strlen('[/img]'));
126
127                 if($orig_body === false) // in case the body ends on a closing image tag
128                         $orig_body = '';
129
130                 $img_start = strpos($orig_body, '[img');
131                 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
132                 $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
133         }
134
135         $new_body = $new_body . $orig_body;
136
137         return array('body' => $new_body, 'images' => $saved_image);
138 }}
139
140 if(! function_exists('item_redir_and_replace_images')) {
141 function item_redir_and_replace_images($body, $images, $cid) {
142
143         $origbody = $body;
144         $newbody = '';
145
146         for($i = 0; $i < count($images); $i++) {
147                 $search = '/\[url\=(.*?)\]\[!#saved_image' . $i . '#!\]\[\/url\]' . '/is';
148                 $replace = '[url=' . z_path() . '/redir/' . $cid
149                            . '?f=1&url=' . '$1' . '][!#saved_image' . $i . '#!][/url]' ;
150
151                 $img_end = strpos($origbody, '[!#saved_image' . $i . '#!][/url]') + strlen('[!#saved_image' . $i . '#!][/url]');
152                 $process_part = substr($origbody, 0, $img_end);
153                 $origbody = substr($origbody, $img_end);
154
155                 $process_part = preg_replace($search, $replace, $process_part);
156                 $newbody = $newbody . $process_part;
157         }
158         $newbody = $newbody . $origbody;
159
160         $cnt = 0;
161         foreach($images as $image) {
162                 // We're depending on the property of 'foreach' (specified on the PHP website) that
163                 // it loops over the array starting from the first element and going sequentially
164                 // to the last element
165                 $newbody = str_replace('[!#saved_image' . $cnt . '#!]', '[img]' . $image . '[/img]', $newbody);
166                 $cnt++;
167         }
168
169         return $newbody;
170 }}
171
172
173
174 function message_content(&$a) {
175
176         $o = '';
177         nav_set_selected('messages');
178
179         if(! local_user()) {
180                 notice( t('Permission denied.') . EOL);
181                 return;
182         }
183
184         $myprofile = $a->get_baseurl(true) . '/profile/' . $a->user['nickname'];
185
186         $tpl = get_markup_template('mail_head.tpl');
187         $header = replace_macros($tpl, array(
188                 '$messages' => t('Messages'),
189                 '$tab_content' => $tab_content
190         ));
191
192
193         if(($a->argc == 3) && ($a->argv[1] === 'drop' || $a->argv[1] === 'dropconv')) {
194                 if(! intval($a->argv[2]))
195                         return;
196
197                 // Check if we should do HTML-based delete confirmation
198                 if($_REQUEST['confirm']) {
199                         // <form> can't take arguments in its "action" parameter
200                         // so add any arguments as hidden inputs
201                         $query = explode_querystring($a->query_string);
202                         $inputs = array();
203                         foreach($query['args'] as $arg) {
204                                 if(strpos($arg, 'confirm=') === false) {
205                                         $arg_parts = explode('=', $arg);
206                                         $inputs[] = array('name' => $arg_parts[0], 'value' => $arg_parts[1]);
207                                 }
208                         }
209
210                         //$a->page['aside'] = '';
211                         return replace_macros(get_markup_template('confirm.tpl'), array(
212                                 '$method' => 'get',
213                                 '$message' => t('Do you really want to delete this message?'),
214                                 '$extra_inputs' => $inputs,
215                                 '$confirm' => t('Yes'),
216                                 '$confirm_url' => $query['base'],
217                                 '$confirm_name' => 'confirmed',
218                                 '$cancel' => t('Cancel'),
219                         ));
220                 }
221                 // Now check how the user responded to the confirmation query
222                 if($_REQUEST['canceled']) {
223                         goaway($a->get_baseurl(true) . '/' . $_SESSION['return_url']);
224                 }
225
226                 $cmd = $a->argv[1];
227                 if($cmd === 'drop') {
228                         $r = q("DELETE FROM `mail` WHERE `id` = %d AND `uid` = %d LIMIT 1",
229                                 intval($a->argv[2]),
230                                 intval(local_user())
231                         );
232                         if($r) {
233                                 info( t('Message deleted.') . EOL );
234                         }
235                         //goaway($a->get_baseurl(true) . '/message' );
236                         goaway($a->get_baseurl(true) . '/' . $_SESSION['return_url']);
237                 }
238                 else {
239                         $r = q("SELECT `parent-uri`,`convid` FROM `mail` WHERE `id` = %d AND `uid` = %d LIMIT 1",
240                                 intval($a->argv[2]),
241                                 intval(local_user())
242                         );
243                         if(count($r)) {
244                                 $parent = $r[0]['parent-uri'];
245                                 $convid = $r[0]['convid'];
246
247                                 $r = q("DELETE FROM `mail` WHERE `parent-uri` = '%s' AND `uid` = %d ",
248                                         dbesc($parent),
249                                         intval(local_user())
250                                 );
251
252                                 // remove diaspora conversation pointer
253                                 // Actually if we do this, we can never receive another reply to that conversation,
254                                 // as we will never again have the info we need to re-create it.
255                                 // We'll just have to orphan it.
256
257                                 //if($convid) {
258                                 //      q("delete from conv where id = %d limit 1",
259                                 //              intval($convid)
260                                 //      );
261                                 //}
262
263                                 if($r)
264                                         info( t('Conversation removed.') . EOL );
265                         }
266                         //goaway($a->get_baseurl(true) . '/message' );
267                         goaway($a->get_baseurl(true) . '/' . $_SESSION['return_url']);
268                 }
269
270         }
271
272         if(($a->argc > 1) && ($a->argv[1] === 'new')) {
273
274                 $o .= $header;
275
276 /*              $plaintext = false;
277                 if(intval(get_pconfig(local_user(),'system','plaintext')))
278                         $plaintext = true;*/
279                 $plaintext = true;
280                 if( local_user() && feature_enabled(local_user(),'richtext') )
281                         $plaintext = false;
282
283
284                 $tpl = get_markup_template('msg-header.tpl');
285                 $a->page['htmlhead'] .= replace_macros($tpl, array(
286                         '$baseurl' => $a->get_baseurl(true),
287                         '$editselect' => (($plaintext) ? 'none' : '/(profile-jot-text|prvmail-text)/'),
288                         '$nickname' => $a->user['nickname'],
289                         '$linkurl' => t('Please enter a link URL:')
290                 ));
291
292                 $tpl = get_markup_template('msg-end.tpl');
293                 $a->page['end'] .= replace_macros($tpl, array(
294                         '$baseurl' => $a->get_baseurl(true),
295                         '$editselect' => (($plaintext) ? 'none' : '/(profile-jot-text|prvmail-text)/'),
296                         '$nickname' => $a->user['nickname'],
297                         '$linkurl' => t('Please enter a link URL:')
298                 ));
299
300                 $preselect = (isset($a->argv[2])?array($a->argv[2]):false);
301
302
303                 $prename = $preurl = $preid = '';
304
305                 if($preselect) {
306                         $r = q("select name, url, id from contact where uid = %d and id = %d limit 1",
307                                 intval(local_user()),
308                                 intval($a->argv[2])
309                         );
310                         if(count($r)) {
311                                 $prename = $r[0]['name'];
312                                 $preurl = $r[0]['url'];
313                                 $preid = $r[0]['id'];
314                         }
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
344                 return $o;
345         }
346
347
348         $_SESSION['return_url'] = $a->query_string;
349
350         if($a->argc == 1) {
351
352                 // List messages
353
354                 $o .= $header;
355
356                 $r = q("SELECT count(*) AS `total` FROM `mail`
357                         WHERE `mail`.`uid` = %d GROUP BY `parent-uri` ORDER BY `created` DESC",
358                         intval(local_user()),
359                         dbesc($myprofile)
360                 );
361
362                 if(count($r)) $a->set_pager_total($r[0]['total']);
363
364                 $r = get_messages(local_user(), $a->pager['start'], $a->pager['itemspage']);
365
366                 if(! count($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                 $plaintext = true;
383                 if( local_user() && feature_enabled(local_user(),'richtext') )
384                         $plaintext = false;
385
386                 $r = q("SELECT `mail`.*, `contact`.`name`, `contact`.`url`, `contact`.`thumb`
387                         FROM `mail` LEFT JOIN `contact` ON `mail`.`contact-id` = `contact`.`id`
388                         WHERE `mail`.`uid` = %d AND `mail`.`id` = %d LIMIT 1",
389                         intval(local_user()),
390                         intval($a->argv[1])
391                 );
392                 if(count($r)) {
393                         $contact_id = $r[0]['contact-id'];
394                         $convid = $r[0]['convid'];
395
396                         $sql_extra = sprintf(" and `mail`.`parent-uri` = '%s' ", dbesc($r[0]['parent-uri']));
397                         if($convid)
398                                 $sql_extra = sprintf(" and ( `mail`.`parent-uri` = '%s' OR `mail`.`convid` = '%d' ) ",
399                                         dbesc($r[0]['parent-uri']),
400                                         intval($convid)
401                                 );
402
403                         $messages = q("SELECT `mail`.*, `contact`.`name`, `contact`.`url`, `contact`.`thumb`
404                                 FROM `mail` LEFT JOIN `contact` ON `mail`.`contact-id` = `contact`.`id`
405                                 WHERE `mail`.`uid` = %d $sql_extra ORDER BY `mail`.`created` ASC",
406                                 intval(local_user())
407                         );
408                 }
409                 if(! count($messages)) {
410                         notice( t('Message not available.') . EOL );
411                         return $o;
412                 }
413
414                 $r = q("UPDATE `mail` SET `seen` = 1 WHERE `parent-uri` = '%s' AND `uid` = %d",
415                         dbesc($r[0]['parent-uri']),
416                         intval(local_user())
417                 );
418
419                 require_once("include/bbcode.php");
420
421                 $tpl = get_markup_template('msg-header.tpl');
422                 $a->page['htmlhead'] .= replace_macros($tpl, array(
423                         '$baseurl' => $a->get_baseurl(true),
424                         '$editselect' => (($plaintext) ? 'none' : '/(profile-jot-text|prvmail-text)/'),
425                         '$nickname' => $a->user['nickname'],
426                         '$linkurl' => t('Please enter a link URL:')
427                 ));
428
429                 $tpl = get_markup_template('msg-end.tpl');
430                 $a->page['end'] .= replace_macros($tpl, array(
431                         '$baseurl' => $a->get_baseurl(true),
432                         '$editselect' => (($plaintext) ? 'none' : '/(profile-jot-text|prvmail-text)/'),
433                         '$nickname' => $a->user['nickname'],
434                         '$linkurl' => t('Please enter a link URL:')
435                 ));
436
437
438                 $mails = array();
439                 $seen = 0;
440                 $unknown = false;
441
442                 foreach($messages as $message) {
443                         if($message['unknown'])
444                                 $unknown = true;
445                         if($message['from-url'] == $myprofile) {
446                                 $from_url = $myprofile;
447                                 $sparkle = '';
448                         }
449                         else {
450                                 $from_url = $a->get_baseurl(true) . '/redir/' . $message['contact-id'];
451                                 $sparkle = ' sparkle';
452                         }
453
454
455                         $extracted = item_extract_images($message['body']);
456                         if($extracted['images'])
457                                 $message['body'] = item_redir_and_replace_images($extracted['body'], $extracted['images'], $message['contact-id']);
458
459                         if($a->theme['template_engine'] === 'internal') {
460                                 $from_name_e = template_escape($message['from-name']);
461                                 $subject_e = template_escape($message['title']);
462                                 $body_e = template_escape(smilies(bbcode($message['body'])));
463                                 $to_name_e = template_escape($message['name']);
464                         }
465                         else {
466                                 $from_name_e = $message['from-name'];
467                                 $subject_e = $message['title'];
468                                 $body_e = smilies(bbcode($message['body']));
469                                 $to_name_e = $message['name'];
470                         }
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' => $message['from-photo'],
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
535         return q("SELECT max(`mail`.`created`) AS `mailcreated`, min(`mail`.`seen`) AS `mailseen`,
536                 `mail`.* , `contact`.`name`, `contact`.`url`, `contact`.`thumb` , `contact`.`network`,
537                 count( * ) as count
538                 FROM `mail` LEFT JOIN `contact` ON `mail`.`contact-id` = `contact`.`id`
539                 WHERE `mail`.`uid` = %d GROUP BY `parent-uri` ORDER BY `mailcreated` DESC  LIMIT %d , %d ",
540                 intval($user), intval($lstart), intval($lend)
541         );
542 }
543
544 function render_messages($msg, $t) {
545
546         $a = get_app();
547
548         $tpl = get_markup_template($t);
549         $rslt = '';
550
551         foreach($msg as $rr) {
552
553                 if($rr['unknown']) {
554                         $participants = sprintf( t("Unknown sender - %s"),$rr['from-name']);
555                 }
556                 elseif (link_compare($rr['from-url'], $myprofile)){
557                         $participants = sprintf( t("You and %s"), $rr['name']);
558                 }
559                 else {
560                         $participants = sprintf( t("%s and You"), $rr['from-name']);
561                 }
562
563                 if($a->theme['template_engine'] === 'internal') {
564                         $subject_e = template_escape((($rr['mailseen']) ? $rr['title'] : '<strong>' . $rr['title'] . '</strong>'));
565                         $body_e = template_escape($rr['body']);
566                         $to_name_e = template_escape($rr['name']);
567                 }
568                 else {
569                         $subject_e = (($rr['mailseen']) ? $rr['title'] : '<strong>' . $rr['title'] . '</strong>');
570                         $body_e = $rr['body'];
571                         $to_name_e = $rr['name'];
572                 }
573
574                 $rslt .= replace_macros($tpl, array(
575                         '$id' => $rr['id'],
576                         '$from_name' => $participants,
577                         '$from_url' => (($rr['network'] === NETWORK_DFRN) ? $a->get_baseurl(true) . '/redir/' . $rr['contact-id'] : $rr['url']),
578                         '$sparkle' => ' sparkle',
579                         '$from_photo' => (($rr['thumb']) ? $rr['thumb'] : $rr['from-photo']),
580                         '$subject' => $subject_e,
581                         '$delete' => t('Delete conversation'),
582                         '$body' => $body_e,
583                         '$to_name' => $to_name_e,
584                         '$date' => datetime_convert('UTC',date_default_timezone_get(),$rr['mailcreated'], t('D, d M Y - g:i A')),
585                                                                                                                         '$ago' => relative_date($rr['mailcreated']),
586                         '$seen' => $rr['mailseen'],
587                         '$count' => sprintf( tt('%d message', '%d messages', $rr['count']), $rr['count']),
588                 ));
589         }
590
591         return $rslt;
592 }