4 use Friendica\Content\Smilies;
5 use Friendica\Core\System;
6 use Friendica\Database\DBM;
8 require_once 'include/acl_selectors.php';
9 require_once 'include/message.php';
11 function message_init(App $a) {
15 if ($a->argc >1 && is_numeric($a->argv[1])) {
16 $tabs = render_messages(get_messages(local_user(),0,5), 'mail_list.tpl');
20 'label' => t('New Message'),
21 'url' => 'message/new',
22 'sel'=> ($a->argv[1] == 'new'),
26 $tpl = get_markup_template('message_side.tpl');
27 $a->page['aside'] = replace_macros($tpl, array(
31 $base = System::baseUrl();
33 $head_tpl = get_markup_template('message-head.tpl');
34 $a->page['htmlhead'] .= replace_macros($head_tpl,array(
35 '$baseurl' => System::baseUrl(true),
39 $end_tpl = get_markup_template('message-end.tpl');
40 $a->page['end'] .= replace_macros($end_tpl,array(
41 '$baseurl' => System::baseUrl(true),
47 function message_post(App $a) {
50 notice( t('Permission denied.') . EOL);
54 $replyto = ((x($_REQUEST,'replyto')) ? notags(trim($_REQUEST['replyto'])) : '');
55 $subject = ((x($_REQUEST,'subject')) ? notags(trim($_REQUEST['subject'])) : '');
56 $body = ((x($_REQUEST,'body')) ? escape_tags(trim($_REQUEST['body'])) : '');
57 $recipient = ((x($_REQUEST,'messageto')) ? intval($_REQUEST['messageto']) : 0 );
59 $ret = send_message($recipient, $body, $subject, $replyto);
64 notice( t('No recipient selected.') . EOL );
68 notice( t('Unable to locate contact information.') . EOL );
71 notice( t('Message could not be sent.') . EOL );
74 notice( t('Message collection failure.') . EOL );
77 info( t('Message sent.') . EOL );
80 // fake it to go back to the input form if no recipient listed
86 goaway($_SESSION['return_url']);
90 // Note: the code in 'item_extract_images' and 'item_redir_and_replace_images'
91 // is identical to the code in include/conversation.php
92 if (! function_exists('item_extract_images')) {
93 function item_extract_images($body) {
95 $saved_image = array();
100 $img_start = strpos($orig_body, '[img');
101 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
102 $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
103 while(($img_st_close !== false) && ($img_end !== false)) {
105 $img_st_close++; // make it point to AFTER the closing bracket
106 $img_end += $img_start;
108 if (! strcmp(substr($orig_body, $img_start + $img_st_close, 5), 'data:')) {
109 // This is an embedded image
111 $saved_image[$cnt] = substr($orig_body, $img_start + $img_st_close, $img_end - ($img_start + $img_st_close));
112 $new_body = $new_body . substr($orig_body, 0, $img_start) . '[!#saved_image' . $cnt . '#!]';
116 $new_body = $new_body . substr($orig_body, 0, $img_end + strlen('[/img]'));
118 $orig_body = substr($orig_body, $img_end + strlen('[/img]'));
120 if ($orig_body === false) // in case the body ends on a closing image tag
123 $img_start = strpos($orig_body, '[img');
124 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
125 $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
128 $new_body = $new_body . $orig_body;
130 return array('body' => $new_body, 'images' => $saved_image);
133 if (! function_exists('item_redir_and_replace_images')) {
134 function item_redir_and_replace_images($body, $images, $cid) {
139 for($i = 0; $i < count($images); $i++) {
140 $search = '/\[url\=(.*?)\]\[!#saved_image' . $i . '#!\]\[\/url\]' . '/is';
141 $replace = '[url=' . System::baseUrl() . '/redir/' . $cid
142 . '?f=1&url=' . '$1' . '][!#saved_image' . $i . '#!][/url]' ;
144 $img_end = strpos($origbody, '[!#saved_image' . $i . '#!][/url]') + strlen('[!#saved_image' . $i . '#!][/url]');
145 $process_part = substr($origbody, 0, $img_end);
146 $origbody = substr($origbody, $img_end);
148 $process_part = preg_replace($search, $replace, $process_part);
149 $newbody = $newbody . $process_part;
151 $newbody = $newbody . $origbody;
154 foreach ($images as $image) {
155 // We're depending on the property of 'foreach' (specified on the PHP website) that
156 // it loops over the array starting from the first element and going sequentially
157 // to the last element
158 $newbody = str_replace('[!#saved_image' . $cnt . '#!]', '[img]' . $image . '[/img]', $newbody);
167 function message_content(App $a) {
170 nav_set_selected('messages');
172 if (! local_user()) {
173 notice( t('Permission denied.') . EOL);
177 $myprofile = System::baseUrl().'/profile/' . $a->user['nickname'];
179 $tpl = get_markup_template('mail_head.tpl');
180 $header = replace_macros($tpl, array(
181 '$messages' => t('Messages'),
182 '$tab_content' => $tab_content
186 if (($a->argc == 3) && ($a->argv[1] === 'drop' || $a->argv[1] === 'dropconv')) {
187 if (! intval($a->argv[2]))
190 // Check if we should do HTML-based delete confirmation
191 if ($_REQUEST['confirm']) {
192 // <form> can't take arguments in its "action" parameter
193 // so add any arguments as hidden inputs
194 $query = explode_querystring($a->query_string);
196 foreach($query['args'] as $arg) {
197 if (strpos($arg, 'confirm=') === false) {
198 $arg_parts = explode('=', $arg);
199 $inputs[] = array('name' => $arg_parts[0], 'value' => $arg_parts[1]);
203 //$a->page['aside'] = '';
204 return replace_macros(get_markup_template('confirm.tpl'), array(
206 '$message' => t('Do you really want to delete this message?'),
207 '$extra_inputs' => $inputs,
208 '$confirm' => t('Yes'),
209 '$confirm_url' => $query['base'],
210 '$confirm_name' => 'confirmed',
211 '$cancel' => t('Cancel'),
214 // Now check how the user responded to the confirmation query
215 if ($_REQUEST['canceled']) {
216 goaway($_SESSION['return_url']);
220 if ($cmd === 'drop') {
221 $r = q("DELETE FROM `mail` WHERE `id` = %d AND `uid` = %d LIMIT 1",
226 info( t('Message deleted.') . EOL );
228 //goaway(System::baseUrl(true) . '/message' );
229 goaway($_SESSION['return_url']);
231 $r = q("SELECT `parent-uri`,`convid` FROM `mail` WHERE `id` = %d AND `uid` = %d LIMIT 1",
235 if (DBM::is_result($r)) {
236 $parent = $r[0]['parent-uri'];
237 $convid = $r[0]['convid'];
239 $r = q("DELETE FROM `mail` WHERE `parent-uri` = '%s' AND `uid` = %d ",
244 // remove diaspora conversation pointer
245 // Actually if we do this, we can never receive another reply to that conversation,
246 // as we will never again have the info we need to re-create it.
247 // We'll just have to orphan it.
250 // q("delete from conv where id = %d limit 1",
256 info( t('Conversation removed.') . EOL );
258 //goaway(System::baseUrl(true) . '/message' );
259 goaway($_SESSION['return_url']);
264 if (($a->argc > 1) && ($a->argv[1] === 'new')) {
268 $tpl = get_markup_template('msg-header.tpl');
269 $a->page['htmlhead'] .= replace_macros($tpl, array(
270 '$baseurl' => System::baseUrl(true),
271 '$nickname' => $a->user['nickname'],
272 '$linkurl' => t('Please enter a link URL:')
275 $tpl = get_markup_template('msg-end.tpl');
276 $a->page['end'] .= replace_macros($tpl, array(
277 '$baseurl' => System::baseUrl(true),
278 '$nickname' => $a->user['nickname'],
279 '$linkurl' => t('Please enter a link URL:')
282 $preselect = (isset($a->argv[2])?array($a->argv[2]):false);
285 $prename = $preurl = $preid = '';
288 $r = q("SELECT `name`, `url`, `id` FROM `contact` WHERE `uid` = %d AND `id` = %d LIMIT 1",
289 intval(local_user()),
292 if (!DBM::is_result($r)) {
293 $r = q("SELECT `name`, `url`, `id` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' LIMIT 1",
294 intval(local_user()),
295 dbesc(normalise_link(base64_decode($a->argv[2])))
299 if (!DBM::is_result($r)) {
300 $r = q("SELECT `name`, `url`, `id` FROM `contact` WHERE `uid` = %d AND `addr` = '%s' LIMIT 1",
301 intval(local_user()),
302 dbesc(base64_decode($a->argv[2]))
306 if (DBM::is_result($r)) {
307 $prename = $r[0]['name'];
308 $preurl = $r[0]['url'];
309 $preid = $r[0]['id'];
310 $preselect = array($preid);
315 $prefill = (($preselect) ? $prename : '');
317 // the ugly select box
319 $select = contact_select('messageto','message-to-select', $preselect, 4, true, false, false, 10);
321 $tpl = get_markup_template('prv_message.tpl');
322 $o .= replace_macros($tpl,array(
323 '$header' => t('Send Private Message'),
325 '$showinputs' => 'true',
326 '$prefill' => $prefill,
327 '$autocomp' => $autocomp,
329 '$subject' => t('Subject:'),
330 '$subjtxt' => ((x($_REQUEST,'subject')) ? strip_tags($_REQUEST['subject']) : ''),
331 '$text' => ((x($_REQUEST,'body')) ? escape_tags(htmlspecialchars($_REQUEST['body'])) : ''),
333 '$yourmessage' => t('Your message:'),
334 '$select' => $select,
336 '$upload' => t('Upload photo'),
337 '$insert' => t('Insert web link'),
338 '$wait' => t('Please wait'),
339 '$submit' => t('Submit')
345 $_SESSION['return_url'] = $a->query_string;
353 $r = q("SELECT count(*) AS `total`, ANY_VALUE(`created`) AS `created` FROM `mail`
354 WHERE `mail`.`uid` = %d GROUP BY `parent-uri` ORDER BY `created` DESC",
358 if (DBM::is_result($r)) {
359 $a->set_pager_total($r[0]['total']);
362 $r = get_messages(local_user(), $a->pager['start'], $a->pager['itemspage']);
364 if (! DBM::is_result($r)) {
365 info( t('No messages.') . EOL);
369 $o .= render_messages($r, 'mail_list.tpl');
376 if (($a->argc > 1) && (intval($a->argv[1]))) {
380 $r = q("SELECT `mail`.*, `contact`.`name`, `contact`.`url`, `contact`.`thumb`
381 FROM `mail` LEFT JOIN `contact` ON `mail`.`contact-id` = `contact`.`id`
382 WHERE `mail`.`uid` = %d AND `mail`.`id` = %d LIMIT 1",
383 intval(local_user()),
386 if (DBM::is_result($r)) {
387 $contact_id = $r[0]['contact-id'];
388 $convid = $r[0]['convid'];
390 $sql_extra = sprintf(" and `mail`.`parent-uri` = '%s' ", dbesc($r[0]['parent-uri']));
392 $sql_extra = sprintf(" and ( `mail`.`parent-uri` = '%s' OR `mail`.`convid` = '%d' ) ",
393 dbesc($r[0]['parent-uri']),
397 $messages = q("SELECT `mail`.*, `contact`.`name`, `contact`.`url`, `contact`.`thumb`
398 FROM `mail` LEFT JOIN `contact` ON `mail`.`contact-id` = `contact`.`id`
399 WHERE `mail`.`uid` = %d $sql_extra ORDER BY `mail`.`created` ASC",
403 if (! count($messages)) {
404 notice( t('Message not available.') . EOL );
408 $r = q("UPDATE `mail` SET `seen` = 1 WHERE `parent-uri` = '%s' AND `uid` = %d",
409 dbesc($r[0]['parent-uri']),
413 require_once("include/bbcode.php");
415 $tpl = get_markup_template('msg-header.tpl');
416 $a->page['htmlhead'] .= replace_macros($tpl, array(
417 '$baseurl' => System::baseUrl(true),
418 '$nickname' => $a->user['nickname'],
419 '$linkurl' => t('Please enter a link URL:')
422 $tpl = get_markup_template('msg-end.tpl');
423 $a->page['end'] .= replace_macros($tpl, array(
424 '$baseurl' => System::baseUrl(true),
425 '$nickname' => $a->user['nickname'],
426 '$linkurl' => t('Please enter a link URL:')
433 foreach($messages as $message) {
434 if ($message['unknown'])
436 if ($message['from-url'] == $myprofile) {
437 $from_url = $myprofile;
439 } elseif ($message['contact-id'] != 0) {
440 $from_url = 'redir/'.$message['contact-id'];
441 $sparkle = ' sparkle';
443 $from_url = $message['from-url']."?zrl=".urlencode($myprofile);
444 $sparkle = ' sparkle';
448 $extracted = item_extract_images($message['body']);
449 if ($extracted['images'])
450 $message['body'] = item_redir_and_replace_images($extracted['body'], $extracted['images'], $message['contact-id']);
452 if ($a->theme['template_engine'] === 'internal') {
453 $from_name_e = template_escape($message['from-name']);
454 $subject_e = template_escape($message['title']);
455 $body_e = template_escape(Smilies::replace(bbcode($message['body'])));
456 $to_name_e = template_escape($message['name']);
458 $from_name_e = $message['from-name'];
459 $subject_e = $message['title'];
460 $body_e = Smilies::replace(bbcode($message['body']));
461 $to_name_e = $message['name'];
464 $contact = get_contact_details_by_url($message['from-url']);
465 if (isset($contact["thumb"]))
466 $from_photo = $contact["thumb"];
468 $from_photo = $message['from-photo'];
471 'id' => $message['id'],
472 'from_name' => $from_name_e,
473 'from_url' => $from_url,
474 'from_addr' => $contact['addr'],
475 'sparkle' => $sparkle,
476 'from_photo' => proxy_url($from_photo, false, PROXY_SIZE_THUMB),
477 'subject' => $subject_e,
479 'delete' => t('Delete message'),
480 'to_name' => $to_name_e,
481 'date' => datetime_convert('UTC',date_default_timezone_get(),$message['created'],'D, d M Y - g:i A'),
482 'ago' => relative_date($message['created']),
485 $seen = $message['seen'];
489 $select = $message['name'] . '<input type="hidden" name="messageto" value="' . $contact_id . '" />';
490 $parent = '<input type="hidden" name="replyto" value="' . $message['parent-uri'] . '" />';
492 $tpl = get_markup_template('mail_display.tpl');
494 if ($a->theme['template_engine'] === 'internal') {
495 $subjtxt_e = template_escape($message['title']);
497 $subjtxt_e = $message['title'];
500 $o = replace_macros($tpl, array(
501 '$thread_id' => $a->argv[1],
502 '$thread_subject' => $message['title'],
503 '$thread_seen' => $seen,
504 '$delete' => t('Delete conversation'),
505 '$canreply' => (($unknown) ? false : '1'),
506 '$unknown_text' => t("No secure communications available. You <strong>may</strong> be able to respond from the sender's profile page."),
510 '$header' => t('Send Reply'),
513 '$subject' => t('Subject:'),
514 '$subjtxt' => $subjtxt_e,
515 '$readonly' => ' readonly="readonly" style="background: #BBBBBB;" ',
516 '$yourmessage' => t('Your message:'),
518 '$select' => $select,
519 '$parent' => $parent,
520 '$upload' => t('Upload photo'),
521 '$insert' => t('Insert web link'),
522 '$submit' => t('Submit'),
523 '$wait' => t('Please wait')
531 function get_messages($user, $lstart, $lend) {
532 //TODO: rewritte with a sub-query to get the first message of each private thread with certainty
533 return q("SELECT max(`mail`.`created`) AS `mailcreated`, min(`mail`.`seen`) AS `mailseen`,
534 ANY_VALUE(`mail`.`id`) AS `id`, ANY_VALUE(`mail`.`uid`) AS `uid`, ANY_VALUE(`mail`.`guid`) AS `guid`,
535 ANY_VALUE(`mail`.`from-name`) AS `from-name`, ANY_VALUE(`mail`.`from-photo`) AS `from-photo`,
536 ANY_VALUE(`mail`.`from-url`) AS `from-url`, ANY_VALUE(`mail`.`contact-id`) AS `contact-id`,
537 ANY_VALUE(`mail`.`convid`) AS `convid`, ANY_VALUE(`mail`.`title`) AS `title`, ANY_VALUE(`mail`.`body`) AS `body`,
538 ANY_VALUE(`mail`.`seen`) AS `seen`, ANY_VALUE(`mail`.`reply`) AS `reply`, ANY_VALUE(`mail`.`replied`) AS `replied`,
539 ANY_VALUE(`mail`.`unknown`) AS `unknown`, ANY_VALUE(`mail`.`uri`) AS `uri`,
541 ANY_VALUE(`mail`.`created`) AS `created`, ANY_VALUE(`contact`.`name`) AS `name`, ANY_VALUE(`contact`.`url`) AS `url`,
542 ANY_VALUE(`contact`.`thumb`) AS `thumb`, ANY_VALUE(`contact`.`network`) AS `network`,
543 count( * ) as `count`
544 FROM `mail` LEFT JOIN `contact` ON `mail`.`contact-id` = `contact`.`id`
545 WHERE `mail`.`uid` = %d GROUP BY `parent-uri` ORDER BY `mailcreated` DESC LIMIT %d , %d ",
546 intval($user), intval($lstart), intval($lend)
550 function render_messages(array $msg, $t) {
554 $tpl = get_markup_template($t);
557 $myprofile = System::baseUrl().'/profile/' . $a->user['nickname'];
559 foreach($msg as $rr) {
562 $participants = sprintf( t("Unknown sender - %s"),$rr['from-name']);
563 elseif (link_compare($rr['from-url'], $myprofile))
564 $participants = sprintf( t("You and %s"), $rr['name']);
566 $participants = sprintf(t("%s and You"), $rr['from-name']);
568 if ($a->theme['template_engine'] === 'internal') {
569 $subject_e = template_escape((($rr['mailseen']) ? $rr['title'] : '<strong>' . $rr['title'] . '</strong>'));
570 $body_e = template_escape($rr['body']);
571 $to_name_e = template_escape($rr['name']);
573 $subject_e = (($rr['mailseen']) ? $rr['title'] : '<strong>' . $rr['title'] . '</strong>');
574 $body_e = $rr['body'];
575 $to_name_e = $rr['name'];
578 $contact = get_contact_details_by_url($rr['url']);
579 if (isset($contact["thumb"]))
580 $from_photo = $contact["thumb"];
582 $from_photo = (($rr['thumb']) ? $rr['thumb'] : $rr['from-photo']);
584 $rslt .= replace_macros($tpl, array(
586 '$from_name' => $participants,
587 '$from_url' => (($rr['network'] === NETWORK_DFRN) ? 'redir/' . $rr['contact-id'] : $rr['url']),
588 '$from_addr' => $contact['addr'],
589 '$sparkle' => ' sparkle',
590 '$from_photo' => proxy_url($from_photo, false, PROXY_SIZE_THUMB),
591 '$subject' => $subject_e,
592 '$delete' => t('Delete conversation'),
594 '$to_name' => $to_name_e,
595 '$date' => datetime_convert('UTC',date_default_timezone_get(),$rr['mailcreated'], t('D, d M Y - g:i A')),
596 '$ago' => relative_date($rr['mailcreated']),
597 '$seen' => $rr['mailseen'],
598 '$count' => sprintf( tt('%d message', '%d messages', $rr['count']), $rr['count']),