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