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