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