4 use Friendica\Content\Smilies;
5 use Friendica\Core\System;
6 use Friendica\Database\DBM;
7 use Friendica\Object\Contact;
9 require_once 'include/acl_selectors.php';
10 require_once 'include/message.php';
12 function message_init(App $a) {
16 if ($a->argc >1 && is_numeric($a->argv[1])) {
17 $tabs = render_messages(get_messages(local_user(),0,5), 'mail_list.tpl');
21 'label' => t('New Message'),
22 'url' => 'message/new',
23 'sel'=> ($a->argv[1] == 'new'),
27 $tpl = get_markup_template('message_side.tpl');
28 $a->page['aside'] = replace_macros($tpl, array(
32 $base = System::baseUrl();
34 $head_tpl = get_markup_template('message-head.tpl');
35 $a->page['htmlhead'] .= replace_macros($head_tpl,array(
36 '$baseurl' => System::baseUrl(true),
40 $end_tpl = get_markup_template('message-end.tpl');
41 $a->page['end'] .= replace_macros($end_tpl,array(
42 '$baseurl' => System::baseUrl(true),
48 function message_post(App $a) {
51 notice( t('Permission denied.') . EOL);
55 $replyto = ((x($_REQUEST,'replyto')) ? notags(trim($_REQUEST['replyto'])) : '');
56 $subject = ((x($_REQUEST,'subject')) ? notags(trim($_REQUEST['subject'])) : '');
57 $body = ((x($_REQUEST,'body')) ? escape_tags(trim($_REQUEST['body'])) : '');
58 $recipient = ((x($_REQUEST,'messageto')) ? intval($_REQUEST['messageto']) : 0 );
60 $ret = send_message($recipient, $body, $subject, $replyto);
65 notice( t('No recipient selected.') . EOL );
69 notice( t('Unable to locate contact information.') . EOL );
72 notice( t('Message could not be sent.') . EOL );
75 notice( t('Message collection failure.') . EOL );
78 info( t('Message sent.') . EOL );
81 // fake it to go back to the input form if no recipient listed
87 goaway($_SESSION['return_url']);
91 // Note: the code in 'item_extract_images' and 'item_redir_and_replace_images'
92 // is identical to the code in include/conversation.php
93 if (! function_exists('item_extract_images')) {
94 function item_extract_images($body) {
96 $saved_image = array();
101 $img_start = strpos($orig_body, '[img');
102 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
103 $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
104 while(($img_st_close !== false) && ($img_end !== false)) {
106 $img_st_close++; // make it point to AFTER the closing bracket
107 $img_end += $img_start;
109 if (! strcmp(substr($orig_body, $img_start + $img_st_close, 5), 'data:')) {
110 // This is an embedded image
112 $saved_image[$cnt] = substr($orig_body, $img_start + $img_st_close, $img_end - ($img_start + $img_st_close));
113 $new_body = $new_body . substr($orig_body, 0, $img_start) . '[!#saved_image' . $cnt . '#!]';
117 $new_body = $new_body . substr($orig_body, 0, $img_end + strlen('[/img]'));
119 $orig_body = substr($orig_body, $img_end + strlen('[/img]'));
121 if ($orig_body === false) // in case the body ends on a closing image tag
124 $img_start = strpos($orig_body, '[img');
125 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
126 $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
129 $new_body = $new_body . $orig_body;
131 return array('body' => $new_body, 'images' => $saved_image);
134 if (! function_exists('item_redir_and_replace_images')) {
135 function item_redir_and_replace_images($body, $images, $cid) {
140 for($i = 0; $i < count($images); $i++) {
141 $search = '/\[url\=(.*?)\]\[!#saved_image' . $i . '#!\]\[\/url\]' . '/is';
142 $replace = '[url=' . System::baseUrl() . '/redir/' . $cid
143 . '?f=1&url=' . '$1' . '][!#saved_image' . $i . '#!][/url]' ;
145 $img_end = strpos($origbody, '[!#saved_image' . $i . '#!][/url]') + strlen('[!#saved_image' . $i . '#!][/url]');
146 $process_part = substr($origbody, 0, $img_end);
147 $origbody = substr($origbody, $img_end);
149 $process_part = preg_replace($search, $replace, $process_part);
150 $newbody = $newbody . $process_part;
152 $newbody = $newbody . $origbody;
155 foreach ($images as $image) {
156 // We're depending on the property of 'foreach' (specified on the PHP website) that
157 // it loops over the array starting from the first element and going sequentially
158 // to the last element
159 $newbody = str_replace('[!#saved_image' . $cnt . '#!]', '[img]' . $image . '[/img]', $newbody);
168 function message_content(App $a) {
171 nav_set_selected('messages');
173 if (! local_user()) {
174 notice( t('Permission denied.') . EOL);
178 $myprofile = System::baseUrl().'/profile/' . $a->user['nickname'];
180 $tpl = get_markup_template('mail_head.tpl');
181 $header = replace_macros($tpl, array(
182 '$messages' => t('Messages'),
183 '$tab_content' => $tab_content
187 if (($a->argc == 3) && ($a->argv[1] === 'drop' || $a->argv[1] === 'dropconv')) {
188 if (! intval($a->argv[2]))
191 // Check if we should do HTML-based delete confirmation
192 if ($_REQUEST['confirm']) {
193 // <form> can't take arguments in its "action" parameter
194 // so add any arguments as hidden inputs
195 $query = explode_querystring($a->query_string);
197 foreach($query['args'] as $arg) {
198 if (strpos($arg, 'confirm=') === false) {
199 $arg_parts = explode('=', $arg);
200 $inputs[] = array('name' => $arg_parts[0], 'value' => $arg_parts[1]);
204 //$a->page['aside'] = '';
205 return replace_macros(get_markup_template('confirm.tpl'), array(
207 '$message' => t('Do you really want to delete this message?'),
208 '$extra_inputs' => $inputs,
209 '$confirm' => t('Yes'),
210 '$confirm_url' => $query['base'],
211 '$confirm_name' => 'confirmed',
212 '$cancel' => t('Cancel'),
215 // Now check how the user responded to the confirmation query
216 if ($_REQUEST['canceled']) {
217 goaway($_SESSION['return_url']);
221 if ($cmd === 'drop') {
222 $r = q("DELETE FROM `mail` WHERE `id` = %d AND `uid` = %d LIMIT 1",
227 info( t('Message deleted.') . EOL );
229 //goaway(System::baseUrl(true) . '/message' );
230 goaway($_SESSION['return_url']);
232 $r = q("SELECT `parent-uri`,`convid` FROM `mail` WHERE `id` = %d AND `uid` = %d LIMIT 1",
236 if (DBM::is_result($r)) {
237 $parent = $r[0]['parent-uri'];
238 $convid = $r[0]['convid'];
240 $r = q("DELETE FROM `mail` WHERE `parent-uri` = '%s' AND `uid` = %d ",
245 // remove diaspora conversation pointer
246 // Actually if we do this, we can never receive another reply to that conversation,
247 // as we will never again have the info we need to re-create it.
248 // We'll just have to orphan it.
251 // q("delete from conv where id = %d limit 1",
257 info( t('Conversation removed.') . EOL );
259 //goaway(System::baseUrl(true) . '/message' );
260 goaway($_SESSION['return_url']);
265 if (($a->argc > 1) && ($a->argv[1] === 'new')) {
269 $tpl = get_markup_template('msg-header.tpl');
270 $a->page['htmlhead'] .= replace_macros($tpl, array(
271 '$baseurl' => System::baseUrl(true),
272 '$nickname' => $a->user['nickname'],
273 '$linkurl' => t('Please enter a link URL:')
276 $tpl = get_markup_template('msg-end.tpl');
277 $a->page['end'] .= replace_macros($tpl, array(
278 '$baseurl' => System::baseUrl(true),
279 '$nickname' => $a->user['nickname'],
280 '$linkurl' => t('Please enter a link URL:')
283 $preselect = (isset($a->argv[2])?array($a->argv[2]):false);
286 $prename = $preurl = $preid = '';
289 $r = q("SELECT `name`, `url`, `id` FROM `contact` WHERE `uid` = %d AND `id` = %d LIMIT 1",
290 intval(local_user()),
293 if (!DBM::is_result($r)) {
294 $r = q("SELECT `name`, `url`, `id` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' LIMIT 1",
295 intval(local_user()),
296 dbesc(normalise_link(base64_decode($a->argv[2])))
300 if (!DBM::is_result($r)) {
301 $r = q("SELECT `name`, `url`, `id` FROM `contact` WHERE `uid` = %d AND `addr` = '%s' LIMIT 1",
302 intval(local_user()),
303 dbesc(base64_decode($a->argv[2]))
307 if (DBM::is_result($r)) {
308 $prename = $r[0]['name'];
309 $preurl = $r[0]['url'];
310 $preid = $r[0]['id'];
311 $preselect = array($preid);
316 $prefill = (($preselect) ? $prename : '');
318 // the ugly select box
320 $select = contact_select('messageto','message-to-select', $preselect, 4, true, false, false, 10);
322 $tpl = get_markup_template('prv_message.tpl');
323 $o .= replace_macros($tpl,array(
324 '$header' => t('Send Private Message'),
326 '$showinputs' => 'true',
327 '$prefill' => $prefill,
328 '$autocomp' => $autocomp,
330 '$subject' => t('Subject:'),
331 '$subjtxt' => ((x($_REQUEST,'subject')) ? strip_tags($_REQUEST['subject']) : ''),
332 '$text' => ((x($_REQUEST,'body')) ? escape_tags(htmlspecialchars($_REQUEST['body'])) : ''),
334 '$yourmessage' => t('Your message:'),
335 '$select' => $select,
337 '$upload' => t('Upload photo'),
338 '$insert' => t('Insert web link'),
339 '$wait' => t('Please wait'),
340 '$submit' => t('Submit')
346 $_SESSION['return_url'] = $a->query_string;
354 $r = q("SELECT count(*) AS `total`, ANY_VALUE(`created`) AS `created` FROM `mail`
355 WHERE `mail`.`uid` = %d GROUP BY `parent-uri` ORDER BY `created` DESC",
359 if (DBM::is_result($r)) {
360 $a->set_pager_total($r[0]['total']);
363 $r = get_messages(local_user(), $a->pager['start'], $a->pager['itemspage']);
365 if (! DBM::is_result($r)) {
366 info( t('No messages.') . EOL);
370 $o .= render_messages($r, 'mail_list.tpl');
377 if (($a->argc > 1) && (intval($a->argv[1]))) {
381 $r = q("SELECT `mail`.*, `contact`.`name`, `contact`.`url`, `contact`.`thumb`
382 FROM `mail` LEFT JOIN `contact` ON `mail`.`contact-id` = `contact`.`id`
383 WHERE `mail`.`uid` = %d AND `mail`.`id` = %d LIMIT 1",
384 intval(local_user()),
387 if (DBM::is_result($r)) {
388 $contact_id = $r[0]['contact-id'];
389 $convid = $r[0]['convid'];
391 $sql_extra = sprintf(" and `mail`.`parent-uri` = '%s' ", dbesc($r[0]['parent-uri']));
393 $sql_extra = sprintf(" and ( `mail`.`parent-uri` = '%s' OR `mail`.`convid` = '%d' ) ",
394 dbesc($r[0]['parent-uri']),
398 $messages = q("SELECT `mail`.*, `contact`.`name`, `contact`.`url`, `contact`.`thumb`
399 FROM `mail` LEFT JOIN `contact` ON `mail`.`contact-id` = `contact`.`id`
400 WHERE `mail`.`uid` = %d $sql_extra ORDER BY `mail`.`created` ASC",
404 if (! count($messages)) {
405 notice( t('Message not available.') . EOL );
409 $r = q("UPDATE `mail` SET `seen` = 1 WHERE `parent-uri` = '%s' AND `uid` = %d",
410 dbesc($r[0]['parent-uri']),
414 require_once("include/bbcode.php");
416 $tpl = get_markup_template('msg-header.tpl');
417 $a->page['htmlhead'] .= replace_macros($tpl, array(
418 '$baseurl' => System::baseUrl(true),
419 '$nickname' => $a->user['nickname'],
420 '$linkurl' => t('Please enter a link URL:')
423 $tpl = get_markup_template('msg-end.tpl');
424 $a->page['end'] .= replace_macros($tpl, array(
425 '$baseurl' => System::baseUrl(true),
426 '$nickname' => $a->user['nickname'],
427 '$linkurl' => t('Please enter a link URL:')
434 foreach($messages as $message) {
435 if ($message['unknown'])
437 if ($message['from-url'] == $myprofile) {
438 $from_url = $myprofile;
440 } elseif ($message['contact-id'] != 0) {
441 $from_url = 'redir/'.$message['contact-id'];
442 $sparkle = ' sparkle';
444 $from_url = $message['from-url']."?zrl=".urlencode($myprofile);
445 $sparkle = ' sparkle';
449 $extracted = item_extract_images($message['body']);
450 if ($extracted['images'])
451 $message['body'] = item_redir_and_replace_images($extracted['body'], $extracted['images'], $message['contact-id']);
453 $from_name_e = $message['from-name'];
454 $subject_e = $message['title'];
455 $body_e = Smilies::replace(bbcode($message['body']));
456 $to_name_e = $message['name'];
458 $contact = Contact::getDetailsByURL($message['from-url']);
459 if (isset($contact["thumb"]))
460 $from_photo = $contact["thumb"];
462 $from_photo = $message['from-photo'];
465 'id' => $message['id'],
466 'from_name' => $from_name_e,
467 'from_url' => $from_url,
468 'from_addr' => $contact['addr'],
469 'sparkle' => $sparkle,
470 'from_photo' => proxy_url($from_photo, false, PROXY_SIZE_THUMB),
471 'subject' => $subject_e,
473 'delete' => t('Delete message'),
474 'to_name' => $to_name_e,
475 'date' => datetime_convert('UTC',date_default_timezone_get(),$message['created'],'D, d M Y - g:i A'),
476 'ago' => relative_date($message['created']),
479 $seen = $message['seen'];
483 $select = $message['name'] . '<input type="hidden" name="messageto" value="' . $contact_id . '" />';
484 $parent = '<input type="hidden" name="replyto" value="' . $message['parent-uri'] . '" />';
486 $tpl = get_markup_template('mail_display.tpl');
488 $subjtxt_e = $message['title'];
490 $o = replace_macros($tpl, array(
491 '$thread_id' => $a->argv[1],
492 '$thread_subject' => $message['title'],
493 '$thread_seen' => $seen,
494 '$delete' => t('Delete conversation'),
495 '$canreply' => (($unknown) ? false : '1'),
496 '$unknown_text' => t("No secure communications available. You <strong>may</strong> be able to respond from the sender's profile page."),
500 '$header' => t('Send Reply'),
503 '$subject' => t('Subject:'),
504 '$subjtxt' => $subjtxt_e,
505 '$readonly' => ' readonly="readonly" style="background: #BBBBBB;" ',
506 '$yourmessage' => t('Your message:'),
508 '$select' => $select,
509 '$parent' => $parent,
510 '$upload' => t('Upload photo'),
511 '$insert' => t('Insert web link'),
512 '$submit' => t('Submit'),
513 '$wait' => t('Please wait')
521 function get_messages($user, $lstart, $lend) {
522 //TODO: rewritte with a sub-query to get the first message of each private thread with certainty
523 return q("SELECT max(`mail`.`created`) AS `mailcreated`, min(`mail`.`seen`) AS `mailseen`,
524 ANY_VALUE(`mail`.`id`) AS `id`, ANY_VALUE(`mail`.`uid`) AS `uid`, ANY_VALUE(`mail`.`guid`) AS `guid`,
525 ANY_VALUE(`mail`.`from-name`) AS `from-name`, ANY_VALUE(`mail`.`from-photo`) AS `from-photo`,
526 ANY_VALUE(`mail`.`from-url`) AS `from-url`, ANY_VALUE(`mail`.`contact-id`) AS `contact-id`,
527 ANY_VALUE(`mail`.`convid`) AS `convid`, ANY_VALUE(`mail`.`title`) AS `title`, ANY_VALUE(`mail`.`body`) AS `body`,
528 ANY_VALUE(`mail`.`seen`) AS `seen`, ANY_VALUE(`mail`.`reply`) AS `reply`, ANY_VALUE(`mail`.`replied`) AS `replied`,
529 ANY_VALUE(`mail`.`unknown`) AS `unknown`, ANY_VALUE(`mail`.`uri`) AS `uri`,
531 ANY_VALUE(`mail`.`created`) AS `created`, ANY_VALUE(`contact`.`name`) AS `name`, ANY_VALUE(`contact`.`url`) AS `url`,
532 ANY_VALUE(`contact`.`thumb`) AS `thumb`, ANY_VALUE(`contact`.`network`) AS `network`,
533 count( * ) as `count`
534 FROM `mail` LEFT JOIN `contact` ON `mail`.`contact-id` = `contact`.`id`
535 WHERE `mail`.`uid` = %d GROUP BY `parent-uri` ORDER BY `mailcreated` DESC LIMIT %d , %d ",
536 intval($user), intval($lstart), intval($lend)
540 function render_messages(array $msg, $t) {
544 $tpl = get_markup_template($t);
547 $myprofile = System::baseUrl().'/profile/' . $a->user['nickname'];
549 foreach($msg as $rr) {
552 $participants = sprintf( t("Unknown sender - %s"),$rr['from-name']);
553 elseif (link_compare($rr['from-url'], $myprofile))
554 $participants = sprintf( t("You and %s"), $rr['name']);
556 $participants = sprintf(t("%s and You"), $rr['from-name']);
558 $subject_e = (($rr['mailseen']) ? $rr['title'] : '<strong>' . $rr['title'] . '</strong>');
559 $body_e = $rr['body'];
560 $to_name_e = $rr['name'];
562 $contact = Contact::getDetailsByURL($rr['url']);
563 if (isset($contact["thumb"]))
564 $from_photo = $contact["thumb"];
566 $from_photo = (($rr['thumb']) ? $rr['thumb'] : $rr['from-photo']);
568 $rslt .= replace_macros($tpl, array(
570 '$from_name' => $participants,
571 '$from_url' => (($rr['network'] === NETWORK_DFRN) ? 'redir/' . $rr['contact-id'] : $rr['url']),
572 '$from_addr' => $contact['addr'],
573 '$sparkle' => ' sparkle',
574 '$from_photo' => proxy_url($from_photo, false, PROXY_SIZE_THUMB),
575 '$subject' => $subject_e,
576 '$delete' => t('Delete conversation'),
578 '$to_name' => $to_name_e,
579 '$date' => datetime_convert('UTC',date_default_timezone_get(),$rr['mailcreated'], t('D, d M Y - g:i A')),
580 '$ago' => relative_date($rr['mailcreated']),
581 '$seen' => $rr['mailseen'],
582 '$count' => sprintf( tt('%d message', '%d messages', $rr['count']), $rr['count']),