4 +-----------------------------------------------------------------------+
5 | program/steps/mail/func.inc |
7 | This file is part of the RoundCube Webmail client |
8 | Copyright (C) 2005-2008, RoundCube Dev. - Switzerland |
9 | Licensed under the GNU GPL |
12 | Provide webmail functionality and GUI objects |
14 +-----------------------------------------------------------------------+
15 | Author: Thomas Bruederli <roundcube@gmail.com> |
16 +-----------------------------------------------------------------------+
18 $Id: func.inc 2197 2008-12-30 13:30:20Z thomasb $
22 require_once('lib/enriched.inc');
23 require_once('include/rcube_smtp.inc');
25 $EMAIL_ADDRESS_PATTERN = '/([a-z0-9][a-z0-9\-\.\+\_]*@[a-z0-9]([a-z0-9\-][.]?)*[a-z0-9]\\.[a-z]{2,5})/i';
27 // actions that do not require imap connection
28 $NOIMAP_ACTIONS = array('spell', 'addcontact', 'autocomplete', 'upload', 'display-attachment', 'remove-attachment');
31 // log in to imap server
32 if (!in_array($RCMAIL->action, $NOIMAP_ACTIONS) && !$RCMAIL->imap_connect()) {
33 $RCMAIL->kill_session();
35 if ($OUTPUT->ajax_call)
36 $OUTPUT->redirect(array(), 2000);
38 $OUTPUT->set_env('task', 'login');
39 $OUTPUT->send('login');
43 // set imap properties and session vars
44 if ($mbox = get_input_value('_mbox', RCUBE_INPUT_GPC))
45 $IMAP->set_mailbox(($_SESSION['mbox'] = $mbox));
47 $_SESSION['mbox'] = $IMAP->get_mailbox_name();
49 if (!empty($_GET['_page']))
50 $IMAP->set_page(($_SESSION['page'] = intval($_GET['_page'])));
52 // set default sort col/order to session
53 if (!isset($_SESSION['sort_col']))
54 $_SESSION['sort_col'] = $CONFIG['message_sort_col'];
55 if (!isset($_SESSION['sort_order']))
56 $_SESSION['sort_order'] = $CONFIG['message_sort_order'];
58 // set message set for search result
59 if (!empty($_REQUEST['_search']) && isset($_SESSION['search'][$_REQUEST['_search']]))
61 $IMAP->set_search_set($_SESSION['search'][$_REQUEST['_search']]);
62 $OUTPUT->set_env('search_request', $_REQUEST['_search']);
63 $OUTPUT->set_env('search_text', $_SESSION['last_text_search']);
66 // set main env variables, labels and page title
67 if (empty($RCMAIL->action) || $RCMAIL->action == 'list')
69 $mbox_name = $IMAP->get_mailbox_name();
71 if (empty($RCMAIL->action))
73 // initialize searching result if search_filter is used
74 if ($_SESSION['search_filter'] && $_SESSION['search_filter'] != 'ALL')
76 $search_request = md5($mbox_name.$_SESSION['search_filter']);
78 $IMAP->search($mbox_name, $_SESSION['search_filter'], RCMAIL_CHARSET, $_SESSION['sort_col']);
79 $_SESSION['search'][$search_request] = $IMAP->get_search_set();
80 $OUTPUT->set_env('search_request', $search_request);
83 // make sure the message count is refreshed (for default view)
84 $IMAP->messagecount($mbox_name, 'ALL', true);
87 // set current mailbox in client environment
88 $OUTPUT->set_env('mailbox', $mbox_name);
89 $OUTPUT->set_env('quota', $IMAP->get_capability('quota'));
90 $OUTPUT->set_env('delimiter', $IMAP->get_hierarchy_delimiter());
92 if ($CONFIG['trash_mbox'])
93 $OUTPUT->set_env('trash_mailbox', $CONFIG['trash_mbox']);
94 if ($CONFIG['drafts_mbox'])
95 $OUTPUT->set_env('drafts_mailbox', $CONFIG['drafts_mbox']);
96 if ($CONFIG['junk_mbox'])
97 $OUTPUT->set_env('junk_mailbox', $CONFIG['junk_mbox']);
99 if (!$OUTPUT->ajax_call)
100 $OUTPUT->add_label('checkingmail', 'deletemessage', 'movemessagetotrash', 'movingmessage');
102 $OUTPUT->set_pagetitle(rcmail_localize_foldername($mbox_name));
107 * return the message list as HTML table
109 function rcmail_message_list($attrib)
111 global $IMAP, $CONFIG, $COMM_PATH, $OUTPUT;
113 $skin_path = $CONFIG['skin_path'];
114 $image_tag = '<img src="%s%s" alt="%s" />';
116 // check to see if we have some settings for sorting
117 $sort_col = $_SESSION['sort_col'];
118 $sort_order = $_SESSION['sort_order'];
120 // add some labels to client
121 $OUTPUT->add_label('from', 'to');
123 // get message headers
124 $a_headers = $IMAP->list_headers('', '', $sort_col, $sort_order);
126 // add id to message list table if not specified
127 if (!strlen($attrib['id']))
128 $attrib['id'] = 'rcubemessagelist';
130 // allow the following attributes to be added to the <table> tag
131 $attrib_str = create_attrib_string($attrib, array('style', 'class', 'id', 'cellpadding', 'cellspacing', 'border', 'summary'));
133 $out = '<table' . $attrib_str . ">\n";
135 // define list of cols to be displayed based on parameter or config
136 if (empty($attrib['columns']))
137 $a_show_cols = is_array($CONFIG['list_cols']) ? $CONFIG['list_cols'] : array('subject');
139 $a_show_cols = preg_split('/[\s,;]+/', strip_quotes($attrib['columns']));
141 // store column list in a session-variable
142 $_SESSION['list_columns'] = $a_show_cols;
144 // define sortable columns
145 $a_sort_cols = array('subject', 'date', 'from', 'to', 'size');
147 $mbox = $IMAP->get_mailbox_name();
149 // show 'to' instead of from in sent messages
150 if (($mbox==$CONFIG['sent_mbox'] || $mbox==$CONFIG['drafts_mbox']) && ($f = array_search('from', $a_show_cols))
151 && !array_search('to', $a_show_cols))
152 $a_show_cols[$f] = 'to';
154 // add col definition
155 $out .= '<colgroup>';
156 $out .= '<col class="icon" />';
158 foreach ($a_show_cols as $col)
159 $out .= ($col!='attachment') ? sprintf('<col class="%s" />', $col) : '<col class="icon" />';
161 $out .= "</colgroup>\n";
164 $out .= "<thead><tr>\n<td class=\"icon\"> </td>\n";
167 foreach ($a_show_cols as $col)
173 $col_name = sprintf($image_tag, $skin_path, $attrib['unflaggedicon'], '');
176 $col_name = sprintf($image_tag, $skin_path, $attrib['attachmenticon'], '');
179 $col_name = Q(rcube_label($col));
184 if (in_array($col, $a_sort_cols))
186 // have buttons configured
187 if (!empty($attrib['sortdescbutton']) || !empty($attrib['sortascbutton']))
189 $sort = ' ';
192 if (!empty($attrib['sortascbutton']))
194 $sort .= $OUTPUT->button(array(
196 'prop' => $col.'_ASC',
197 'image' => $attrib['sortascbutton'],
198 'align' => 'absmiddle',
199 'title' => 'sortasc'));
203 if (!empty($attrib['sortdescbutton']))
205 $sort .= $OUTPUT->button(array(
207 'prop' => $col.'_DESC',
208 'image' => $attrib['sortdescbutton'],
209 'align' => 'absmiddle',
210 'title' => 'sortdesc'));
213 // just add a link tag to the header
217 '<a href="./#sort" onclick="return %s.command(\'sort\',\'%s\',this)" title="%s">%s</a>',
220 rcube_label('sortby'),
225 $sort_class = $col==$sort_col ? " sorted$sort_order" : '';
227 // put it all together
228 if ($col!='attachment')
229 $out .= '<td class="'.$col.$sort_class.'" id="rcm'.$col.'">' . "$col_name$sort</td>\n";
231 $out .= '<td class="icon" id="rcm'.$col.'">' . "$col_name$sort</td>\n";
234 $out .= "</tr></thead>\n<tbody>\n";
236 // no messages in this mailbox
237 if (!sizeof($a_headers))
238 $OUTPUT->show_message('nomessagesfound', 'notice');
241 $a_js_message_arr = array();
243 // create row for each message
244 foreach ($a_headers as $i => $header) //while (list($i, $header) = each($a_headers))
246 $message_icon = $attach_icon = $flagged_icon = '';
247 $js_row_arr = array();
248 $zebra_class = $i%2 ? ' even' : ' odd';
250 // set messag attributes to javascript array
251 if ($header->deleted)
252 $js_row_arr['deleted'] = true;
254 $js_row_arr['unread'] = true;
255 if ($header->answered)
256 $js_row_arr['replied'] = true;
257 if ($header->forwarded)
258 $js_row_arr['forwarded'] = true;
259 if ($header->flagged)
260 $js_row_arr['flagged'] = true;
263 if ($attrib['deletedicon'] && $header->deleted)
264 $message_icon = $attrib['deletedicon'];
265 else if ($attrib['repliedicon'] && $header->answered)
267 if ($attrib['forwardedrepliedicon'] && $header->forwarded)
268 $message_icon = $attrib['forwardedrepliedicon'];
270 $message_icon = $attrib['repliedicon'];
272 else if ($attrib['forwardedicon'] && $header->forwarded)
273 $message_icon = $attrib['forwardedicon'];
274 else if ($attrib['unreadicon'] && !$header->seen)
275 $message_icon = $attrib['unreadicon'];
276 else if ($attrib['messageicon'])
277 $message_icon = $attrib['messageicon'];
279 if ($attrib['flaggedicon'] && $header->flagged)
280 $flagged_icon = $attrib['flaggedicon'];
281 else if ($attrib['unflaggedicon'] && !$header->flagged)
282 $flagged_icon = $attrib['unflaggedicon'];
284 // set attachment icon
285 if ($attrib['attachmenticon'] && preg_match("/multipart\/m/i", $header->ctype))
286 $attach_icon = $attrib['attachmenticon'];
288 $out .= sprintf('<tr id="rcmrow%d" class="message%s%s%s%s">'."\n",
290 $header->seen ? '' : ' unread',
291 $header->deleted ? ' deleted' : '',
292 $header->flagged ? ' flagged' : '',
295 $out .= sprintf("<td class=\"icon\">%s</td>\n", $message_icon ? sprintf($image_tag, $skin_path, $message_icon, '') : '');
298 if (!empty($header->charset))
299 $IMAP->set_charset($header->charset);
302 foreach ($a_show_cols as $col)
304 if ($col=='from' || $col=='to')
305 $cont = Q(rcmail_address_string($header->$col, 3, false, $attrib['addicon']), 'show');
306 else if ($col=='subject')
308 $action = $mbox==$CONFIG['drafts_mbox'] ? 'compose' : 'show';
309 $uid_param = $mbox==$CONFIG['drafts_mbox'] ? '_draft_uid' : '_uid';
310 $cont = abbreviate_string(trim($IMAP->decode_header($header->$col)), 160);
311 if (empty($cont)) $cont = rcube_label('nosubject');
312 $cont = sprintf('<a href="%s" onclick="return rcube_event.cancel(event)">%s</a>', Q(rcmail_url($action, array($uid_param=>$header->uid, '_mbox'=>$mbox))), Q($cont));
314 else if ($col=='flag')
315 $cont = $flagged_icon ? sprintf($image_tag, $skin_path, $flagged_icon, '') : '';
316 else if ($col=='size')
317 $cont = show_bytes($header->$col);
318 else if ($col=='date')
319 $cont = format_date($header->date);
321 $cont = Q($header->$col);
323 if ($col!='attachment')
324 $out .= '<td class="'.$col.'">' . $cont . "</td>\n";
326 $out .= sprintf("<td class=\"icon\">%s</td>\n", $attach_icon ? sprintf($image_tag, $skin_path, $attach_icon, '') : ' ');
331 if (sizeof($js_row_arr))
332 $a_js_message_arr[$header->uid] = $js_row_arr;
335 // complete message table
336 $out .= "</tbody></table>\n";
338 $message_count = $IMAP->messagecount();
341 $OUTPUT->add_gui_object('mailcontframe', 'mailcontframe');
342 $OUTPUT->add_gui_object('messagelist', $attrib['id']);
343 $OUTPUT->set_env('messagecount', $message_count);
344 $OUTPUT->set_env('current_page', $IMAP->list_page);
345 $OUTPUT->set_env('pagecount', ceil($message_count/$IMAP->page_size));
346 $OUTPUT->set_env('sort_col', $sort_col);
347 $OUTPUT->set_env('sort_order', $sort_order);
349 if ($attrib['messageicon'])
350 $OUTPUT->set_env('messageicon', $skin_path . $attrib['messageicon']);
351 if ($attrib['deletedicon'])
352 $OUTPUT->set_env('deletedicon', $skin_path . $attrib['deletedicon']);
353 if ($attrib['unreadicon'])
354 $OUTPUT->set_env('unreadicon', $skin_path . $attrib['unreadicon']);
355 if ($attrib['repliedicon'])
356 $OUTPUT->set_env('repliedicon', $skin_path . $attrib['repliedicon']);
357 if ($attrib['forwardedicon'])
358 $OUTPUT->set_env('forwardedicon', $skin_path . $attrib['forwardedicon']);
359 if ($attrib['forwardedrepliedicon'])
360 $OUTPUT->set_env('forwardedrepliedicon', $skin_path . $attrib['forwardedrepliedicon']);
361 if ($attrib['attachmenticon'])
362 $OUTPUT->set_env('attachmenticon', $skin_path . $attrib['attachmenticon']);
363 if ($attrib['flaggedicon'])
364 $OUTPUT->set_env('flaggedicon', $skin_path . $attrib['flaggedicon']);
365 if ($attrib['unflaggedicon'])
366 $OUTPUT->set_env('unflaggedicon', $skin_path . $attrib['unflaggedicon']);
368 $OUTPUT->set_env('messages', $a_js_message_arr);
369 $OUTPUT->set_env('coltypes', $a_show_cols);
371 $OUTPUT->include_script('list.js');
378 * return javascript commands to add rows to the message list
380 function rcmail_js_message_list($a_headers, $insert_top=FALSE)
382 global $CONFIG, $IMAP, $OUTPUT;
384 if (empty($_SESSION['list_columns']))
385 $a_show_cols = is_array($CONFIG['list_cols']) ? $CONFIG['list_cols'] : array('subject');
387 $a_show_cols = $_SESSION['list_columns'];
389 $mbox = $IMAP->get_mailbox_name();
391 // show 'to' instead of from in sent messages
392 if (($mbox == $CONFIG['sent_mbox'] || $mbox == $CONFIG['drafts_mbox'])
393 && (($f = array_search('from', $a_show_cols)) !== false) && array_search('to', $a_show_cols) === false)
394 $a_show_cols[$f] = 'to';
396 $OUTPUT->command('set_message_coltypes', $a_show_cols);
398 // loop through message headers
399 foreach ($a_headers as $n => $header)
401 $a_msg_cols = array();
402 $a_msg_flags = array();
407 if (!empty($header->charset))
408 $IMAP->set_charset($header->charset);
410 // remove 'attachment' and 'flag' columns, we don't need them here
411 if(($key = array_search('attachment', $a_show_cols)) !== FALSE)
412 unset($a_show_cols[$key]);
413 if(($key = array_search('flag', $a_show_cols)) !== FALSE)
414 unset($a_show_cols[$key]);
416 // format each col; similar as in rcmail_message_list()
417 foreach ($a_show_cols as $col)
419 if ($col=='from' || $col=='to')
420 $cont = Q(rcmail_address_string($header->$col, 3), 'show');
421 else if ($col=='subject')
423 $action = $mbox==$CONFIG['drafts_mbox'] ? 'compose' : 'show';
424 $uid_param = $mbox==$CONFIG['drafts_mbox'] ? '_draft_uid' : '_uid';
425 $cont = abbreviate_string(trim($IMAP->decode_header($header->$col)), 160);
426 if (!$cont) $cont = rcube_label('nosubject');
427 $cont = sprintf('<a href="%s" onclick="return rcube_event.cancel(event)">%s</a>', Q(rcmail_url($action, array($uid_param=>$header->uid, '_mbox'=>$mbox))), Q($cont));
429 else if ($col=='size')
430 $cont = show_bytes($header->$col);
431 else if ($col=='date')
432 $cont = format_date($header->date);
434 $cont = Q($header->$col);
436 $a_msg_cols[$col] = $cont;
439 $a_msg_flags['deleted'] = $header->deleted ? 1 : 0;
440 $a_msg_flags['unread'] = $header->seen ? 0 : 1;
441 $a_msg_flags['replied'] = $header->answered ? 1 : 0;
442 $a_msg_flags['forwarded'] = $header->forwarded ? 1 : 0;
443 $a_msg_flags['flagged'] = $header->flagged ? 1 : 0;
445 $OUTPUT->command('add_message_row',
449 preg_match("/multipart\/m/i", $header->ctype),
456 * return an HTML iframe for loading mail content
458 function rcmail_messagecontent_frame($attrib)
462 if (empty($attrib['id']))
463 $attrib['id'] = 'rcmailcontentwindow';
465 $attrib['name'] = $attrib['id'];
467 $OUTPUT->set_env('contentframe', $attrib['id']);
468 $OUTPUT->set_env('blankpage', $attrib['src'] ? $OUTPUT->abs_url($attrib['src']) : 'program/blank.gif');
470 return html::iframe($attrib);
477 function rcmail_messagecount_display($attrib)
479 global $IMAP, $OUTPUT;
482 $attrib['id'] = 'rcmcountdisplay';
484 $OUTPUT->add_gui_object('countdisplay', $attrib['id']);
486 return html::span($attrib, rcmail_get_messagecount_text());
493 function rcmail_quota_display($attrib)
495 global $OUTPUT, $COMM_PATH;
498 $attrib['id'] = 'rcmquotadisplay';
500 if(isset($attrib['display']))
501 $_SESSION['quota_display'] = $attrib['display'];
503 $OUTPUT->add_gui_object('quotadisplay', $attrib['id']);
505 return html::span($attrib, rcmail_quota_content(NULL, $attrib));
512 function rcmail_quota_content($quota=NULL, $attrib=NULL)
514 global $IMAP, $COMM_PATH, $RCMAIL;
516 $display = isset($_SESSION['quota_display']) ? $_SESSION['quota_display'] : '';
518 if (is_array($quota) && !empty($quota['used']) && !empty($quota['total']))
520 if (!isset($quota['percent']))
521 $quota['percent'] = $quota['used'] / $quota['total'];
523 elseif (!$IMAP->get_capability('QUOTA'))
524 return rcube_label('unknown');
526 $quota = $IMAP->get_quota();
528 if ($quota && !($quota['total']==0 && $RCMAIL->config->get('quota_zero_as_unlimited')))
530 $quota_text = sprintf('%s / %s (%.0f%%)',
531 show_bytes($quota['used'] * 1024),
532 show_bytes($quota['total'] * 1024),
535 // show quota as image (by Brett Patterson)
536 if ($display == 'image' && function_exists('imagegif'))
538 if (!$attrib['width'])
539 $attrib['width'] = isset($_SESSION['quota_width']) ? $_SESSION['quota_width'] : 100;
541 $_SESSION['quota_width'] = $attrib['width'];
543 if (!$attrib['height'])
544 $attrib['height'] = isset($_SESSION['quota_height']) ? $_SESSION['quota_height'] : 14;
546 $_SESSION['quota_height'] = $attrib['height'];
548 $quota_text = sprintf('<img src="./bin/quotaimg.php?u=%s&q=%d&w=%d&h=%d" width="%d" height="%d" alt="%s" title="%s / %s" />',
549 $quota['used'], $quota['total'],
550 $attrib['width'], $attrib['height'],
551 $attrib['width'], $attrib['height'],
553 show_bytes($quota['used'] * 1024),
554 show_bytes($quota['total'] * 1024));
558 $quota_text = rcube_label('unlimited');
567 function rcmail_get_messagecount_text($count=NULL, $page=NULL)
569 global $IMAP, $MESSAGE;
571 if (isset($MESSAGE->index))
573 return rcube_label(array('name' => 'messagenrof',
574 'vars' => array('nr' => $MESSAGE->index+1,
575 'count' => $count!==NULL ? $count : $IMAP->messagecount())));
579 $page = $IMAP->list_page;
581 $start_msg = ($page-1) * $IMAP->page_size + 1;
582 $max = $count!==NULL ? $count : $IMAP->messagecount();
585 $out = rcube_label('mailboxempty');
587 $out = rcube_label(array('name' => 'messagesfromto',
588 'vars' => array('from' => $start_msg,
589 'to' => min($max, $start_msg + $IMAP->page_size - 1),
598 function rcmail_mailbox_name_display($attrib)
603 $attrib['id'] = 'rcmmailboxname';
605 $RCMAIL->output->add_gui_object('mailboxname', $attrib['id']);
607 return html::span($attrib, rcmail_get_mailbox_name_text());
610 function rcmail_get_mailbox_name_text()
613 return rcmail_localize_foldername($RCMAIL->imap->get_mailbox_name());
618 * Convert the given message part to proper HTML
619 * which can be displayed the message view
621 * @param object rcube_message_part Message part
622 * @param bool True if external objects (ie. images ) are allowed
623 * @param bool True if part should be converted to plaintext
624 * @return string Formatted HTML string
626 function rcmail_print_body($part, $p = array())
628 global $REMOTE_OBJECTS;
630 $p += array('safe' => false, 'plain' => false, 'inline_html' => true);
632 // convert html to text/plain
633 if ($part->ctype_secondary == 'html' && $p['plain']) {
634 $txt = new html2text($part->body, false, true);
635 $body = $txt->get_text();
636 $part->ctype_secondary = 'plain';
639 else if ($part->ctype_secondary == 'html') {
642 // special replacements (not properly handled by washtml class)
643 $html_search = array(
644 '/(<\/nobr>)(\s+)(<nobr>)/i', // space(s) between <NOBR>
645 '/(<[\/]*st1:[^>]+>)/i', // Microsoft's Smart Tags <ST1>
646 '/<\/?rte_text>/i', // Rich Text Editor tags (#1485647)
647 '/<title>.*<\/title>/i', // PHP bug #32547 workaround: remove title tag
648 '/<html[^>]*>/im', // malformed html: remove html tags (#1485139)
649 '/<\/html>/i', // malformed html: remove html tags (#1485139)
650 '/^[\xFE\xFF\xBB\xBF\x00]+((?:<\!doctype|\<html))/im', // remove byte-order mark (only outlook?)
652 $html_replace = array(
653 '\\1'.' '.'\\3',
661 $html = preg_replace($html_search, $html_replace, $html);
663 // charset was converted to UTF-8 in rcube_imap::get_message_part() -> change charset specification in HTML accordingly
664 $charset_pattern = '/(\s+content=[\'"]?\w+\/\w+;\s*charset)=([a-z0-9-_]+)/i';
665 if (preg_match($charset_pattern, $html)) {
666 $html = preg_replace($charset_pattern, '\\1='.RCMAIL_CHARSET, $html);
669 // add head for malformed messages, washtml cannot work without that
670 if (!preg_match('/<head[^>]*>(.*)<\/head>/Uims', $html))
671 $html = '<head></head>'. $html;
672 $html = substr_replace($html, '<meta http-equiv="content-type" content="text/html; charset='.RCMAIL_CHARSET.'" />', intval(stripos($html, '<head>')+6), 0);
675 // clean HTML with washhtml by Frederic Motte
677 'show_washed' => false,
678 'allow_remote' => $p['safe'],
679 'blocked_src' => "./program/blocked.gif",
680 'charset' => RCMAIL_CHARSET,
681 'cid_map' => $part->replaces,
682 'html_elements' => array('body'),
685 if (!$p['inline_html']) {
686 $wash_opts['html_elements'] = array('html','head','title','body');
689 $washer = new washtml($wash_opts);
690 $washer->add_callback('form', 'rcmail_washtml_callback');
692 if ($p['safe']) { // allow CSS styles, will be sanitized by rcmail_washtml_callback()
693 $washer->add_callback('style', 'rcmail_washtml_callback');
696 $body = $washer->wash($html);
697 $REMOTE_OBJECTS = $washer->extlinks;
702 else if ($part->ctype_secondary=='enriched') {
703 $part->ctype_secondary = 'html';
704 return Q(enriched_to_html($part->body), 'show');
710 /**** assert plaintext ****/
712 // make links and email-addresses clickable
713 $convert_patterns = $convert_replaces = $replace_strings = array();
715 $url_chars = 'a-z0-9_\-\+\*\$\/&%=@#:;';
716 $url_chars_within = '\?\.~,!';
718 $convert_patterns[] = "/([\w]+):\/\/([a-z0-9\-\.]+[a-z]{2,4}([$url_chars$url_chars_within]*[$url_chars])?)/ie";
719 $convert_replaces[] = "rcmail_str_replacement('<a href=\"\\1://\\2\" target=\"_blank\">\\1://\\2</a>', \$replace_strings)";
721 $convert_patterns[] = "/([^\/:]|\s)(www\.)([a-z0-9\-]{2,}[a-z]{2,4}([$url_chars$url_chars_within]*[$url_chars])?)/ie";
722 $convert_replaces[] = "rcmail_str_replacement('\\1<a href=\"http://\\2\\3\" target=\"_blank\">\\2\\3</a>', \$replace_strings)";
724 $convert_patterns[] = '/([a-z0-9][a-z0-9\-\.\+\_]*@[a-z0-9]([a-z0-9\-][.]?)*[a-z0-9]\\.[a-z]{2,5})/ie';
725 $convert_replaces[] = "rcmail_str_replacement('<a href=\"mailto:\\1\" onclick=\"return ".JS_OBJECT_NAME.".command(\'compose\',\'\\1\',this)\">\\1</a>', \$replace_strings)";
727 // search for patterns like links and e-mail addresses
728 $body = preg_replace($convert_patterns, $convert_replaces, $body);
730 // split body into single lines
731 $a_lines = preg_split('/\r?\n/', $body);
734 // colorize quoted parts
735 for ($n=0; $n < sizeof($a_lines); $n++) {
736 $line = $a_lines[$n];
740 if (preg_match('/^(>+\s*)+/', $line, $regs)) {
741 $q = strlen(preg_replace('/\s/', '', $regs[0]));
742 $line = substr($line, strlen($regs[0]));
744 if ($q > $quote_level)
745 $quotation = str_repeat('<blockquote>', $q - $quote_level);
746 else if ($q < $quote_level)
747 $quotation = str_repeat("</blockquote>", $quote_level - $q);
749 else if ($quote_level > 0)
750 $quotation = str_repeat("</blockquote>", $quote_level);
753 $a_lines[$n] = $quotation . Q($line, 'replace', false); // htmlquote plaintext
756 // insert the links for urls and mailtos
757 $body = preg_replace("/##string_replacement\{([0-9]+)\}##/e", "\$replace_strings[\\1]", join("\n", $a_lines));
759 return html::tag('pre', array(), $body);
763 * add a string to the replacement array and return a replacement string
765 function rcmail_str_replacement($str, &$rep)
768 $rep[$count] = stripslashes($str);
769 return "##string_replacement{".($count++)."}##";
774 * Callback function for washtml cleaning class
776 function rcmail_washtml_callback($tagname, $attrib, $content)
780 $out = html::div('form', $content);
784 // decode all escaped entities and reduce to ascii strings
785 $stripped = preg_replace('/[^a-zA-Z\(:]/', '', rcmail_xss_entitiy_decode($content));
787 // now check for evil strings like expression, behavior or url()
788 if (!preg_match('/expression|behavior|url\(|import/', $stripped)) {
789 $out = html::tag('style', array('type' => 'text/css'), $content);
802 * return table with message headers
804 function rcmail_message_headers($attrib, $headers=NULL)
806 global $IMAP, $OUTPUT, $MESSAGE, $PRINT_MODE, $CONFIG;
809 // keep header table attrib
810 if (is_array($attrib) && !$sa_attrib)
811 $sa_attrib = $attrib;
812 else if (!is_array($attrib) && is_array($sa_attrib))
813 $attrib = $sa_attrib;
816 if (!isset($MESSAGE))
819 // get associative array of headers object
821 $headers = is_object($MESSAGE->headers) ? get_object_vars($MESSAGE->headers) : $MESSAGE->headers;
825 // allow the following attributes to be added to the <table> tag
826 $attrib_str = create_attrib_string($attrib, array('style', 'class', 'id', 'cellpadding', 'cellspacing', 'border', 'summary'));
827 $out = '<table' . $attrib_str . ">\n";
829 // show these headers
830 $standard_headers = array('subject', 'from', 'to', 'cc', 'bcc', 'replyto', 'date');
832 foreach ($standard_headers as $hkey)
834 if (!$headers[$hkey])
840 $header_value = format_date($headers[$hkey], $CONFIG['date_long'] ? $CONFIG['date_long'] : 'x');
842 $header_value = format_date($headers[$hkey]);
844 else if ($hkey == 'replyto')
846 if ($headers['replyto'] != $headers['from'])
847 $header_value = Q(rcmail_address_string($headers['replyto'], null, true, $attrib['addicon']), 'show');
851 else if (in_array($hkey, array('from', 'to', 'cc', 'bcc')))
852 $header_value = Q(rcmail_address_string($headers[$hkey], null, true, $attrib['addicon']), 'show');
853 else if ($hkey == 'subject' && empty($headers[$hkey]))
854 $header_value = Q(rcube_label('nosubject'));
856 $header_value = Q(trim($IMAP->decode_header($headers[$hkey])));
859 $out .= '<td class="header-title">'.Q(rcube_label($hkey)).": </td>\n";
860 $out .= '<td class="'.$hkey.'" width="90%">'.$header_value."</td>\n</tr>";
864 // all headers division
865 $out .= "\n".'<tr><td colspan="2" class="more-headers show-headers"
866 onclick="return '.JS_OBJECT_NAME.'.command(\'load-headers\', \'\', this)"></td></tr>';
867 $out .= "\n".'<tr id="all-headers"><td colspan="2" class="all"><div id="headers-source"></div></td></tr>';
869 $OUTPUT->add_gui_object('all_headers_row', 'all-headers');
870 $OUTPUT->add_gui_object('all_headers_box', 'headers-source');
872 $out .= "\n</table>\n\n";
874 return $header_count ? $out : '';
879 * Handler for the 'messagebody' GUI object
881 * @param array Named parameters
882 * @return string HTML content showing the message body
884 function rcmail_message_body($attrib)
886 global $CONFIG, $OUTPUT, $MESSAGE, $IMAP, $REMOTE_OBJECTS;
888 if (!is_array($MESSAGE->parts) && empty($MESSAGE->body))
892 $attrib['id'] = 'rcmailMsgBody';
894 $safe_mode = $MESSAGE->is_safe || intval($_GET['_safe']);
897 $header_attrib = array();
898 foreach ($attrib as $attr => $value)
899 if (preg_match('/^headertable([a-z]+)$/i', $attr, $regs))
900 $header_attrib[$regs[1]] = $value;
902 if (!empty($MESSAGE->parts))
904 foreach ($MESSAGE->parts as $i => $part)
906 if ($part->type == 'headers')
907 $out .= rcmail_message_headers(sizeof($header_attrib) ? $header_attrib : NULL, $part->headers);
908 else if ($part->type == 'content')
910 if (empty($part->ctype_parameters) || empty($part->ctype_parameters['charset']))
911 $part->ctype_parameters['charset'] = $MESSAGE->headers->charset;
913 // fetch part if not available
914 if (!isset($part->body))
915 $part->body = $MESSAGE->get_part_content($part->mime_id);
917 $body = rcmail_print_body($part, array('safe' => $safe_mode, 'plain' => !$CONFIG['prefer_html']));
919 if ($part->ctype_secondary == 'html')
920 $out .= html::div('message-htmlpart', rcmail_html4inline($body, $attrib['id']));
922 $out .= html::div('message-part', $body);
927 $out .= html::div('message-part', html::tag('pre', array(), Q($MESSAGE->body)));
930 $ctype_primary = strtolower($MESSAGE->structure->ctype_primary);
931 $ctype_secondary = strtolower($MESSAGE->structure->ctype_secondary);
933 // list images after mail body
934 if ($CONFIG['inline_images']
935 && $ctype_primary == 'multipart'
936 && !empty($MESSAGE->attachments)
937 && !strstr($message_body, '<html'))
939 foreach ($MESSAGE->attachments as $attach_prop) {
940 if (strpos($attach_prop->mimetype, 'image/') === 0) {
941 $out .= html::tag('hr') . html::p(array('align' => "center"),
943 'src' => $MESSAGE->get_part_url($attach_prop->mime_id),
944 'title' => $attach_prop->filename,
945 'alt' => $attach_prop->filename,
951 // tell client that there are blocked remote objects
952 if ($REMOTE_OBJECTS && !$safe_mode)
953 $OUTPUT->set_env('blockedobjects', true);
955 return html::div($attrib, $out);
961 * modify a HTML message that it can be displayed inside a HTML page
963 function rcmail_html4inline($body, $container_id)
967 $body_lc = strtolower($body);
969 // check for <base href>
970 if (preg_match(($base_reg = '/(<base.*href=["\']?)([hftps]{3,5}:\/{2}[^"\'\s]+)([^<]*>)/i'), $body, $base_regs))
971 $base_url = $base_regs[2];
974 while (($pos = strpos($body_lc, '<style', $last_style_pos)) && ($pos2 = strpos($body_lc, '</style>', $pos)))
976 $pos = strpos($body_lc, '>', $pos)+1;
978 // replace all css definitions with #container [def]
979 $styles = rcmail_mod_css_styles(substr($body, $pos, $pos2-$pos), $container_id, $base_url);
981 $body = substr($body, 0, $pos) . $styles . substr($body, $pos2);
982 $body_lc = strtolower($body);
983 $last_style_pos = $pos2;
986 // resolve <base href>
989 $body = preg_replace('/(src|background|href)=(["\']?)([\.\/]+[^"\'\s]+)(\2|\s|>)/Uie', "'\\1=\"'.make_absolute_url('\\3', '$base_url').'\"'", $body);
990 $body = preg_replace('/(url\s*\()(["\']?)([\.\/]+[^"\'\)\s]+)(\2)\)/Uie', "'\\1\''.make_absolute_url('\\3', '$base_url').'\')'", $body);
991 $body = preg_replace($base_reg, '', $body);
994 // modify HTML links to open a new window if clicked
995 $body = preg_replace('/<(a|link)\s+([^>]+)>/Uie', "rcmail_alter_html_link('\\1','\\2', '$container_id');", $body);
997 // add comments arround html and other tags
998 $out = preg_replace(array(
999 '/(<!DOCTYPE[^>]*>)/i',
1000 '/(<\?xml[^>]*>)/i',
1001 '/(<\/?html[^>]*>)/i',
1002 '/(<\/?head[^>]*>)/i',
1003 '/(<title[^>]*>.*<\/title>)/Ui',
1004 '/(<\/?meta[^>]*>)/i'),
1008 $out = preg_replace(
1009 array('/<body([^>]*)>/i', '/<\/body>/i'),
1010 array('<div class="rcmBody"\\1>', '</div>'),
1013 // quote <? of php and xml files that are specified as text/html
1014 $out = preg_replace(array('/<\?/', '/\?>/'), array('<?', '?>'), $out);
1021 * parse link attributes and set correct target
1023 function rcmail_alter_html_link($tag, $attrs, $container_id)
1025 $attrib = parse_attrib_string($attrs);
1028 if ($tag == 'link' && preg_match('/^https?:\/\//i', $attrib['href'])) {
1029 $attrib['href'] = "./bin/modcss.php?u=" . urlencode($attrib['href']) . "&c=" . urlencode($container_id);
1032 else if (stristr((string)$attrib['href'], 'mailto:')) {
1033 $attrib['onclick'] = sprintf(
1034 "return %s.command('compose','%s',this)",
1036 JQ(substr($attrib['href'], 7)));
1038 else if (!empty($attrib['href']) && $attrib['href'][0] != '#') {
1039 $attrib['target'] = '_blank';
1042 return "<$tag" . html::attrib_string($attrib, array('href','name','target','onclick','id','class','style','title','rel','type','media')) . $end;
1047 * decode address string and re-format it as HTML links
1049 function rcmail_address_string($input, $max=null, $linked=false, $addicon=null)
1051 global $IMAP, $PRINT_MODE, $CONFIG, $OUTPUT, $EMAIL_ADDRESS_PATTERN;
1053 $a_parts = $IMAP->decode_address_list($input);
1055 if (!sizeof($a_parts))
1058 $c = count($a_parts);
1062 foreach ($a_parts as $part) {
1065 $out .= sprintf('%s <%s>', Q($part['name']), $part['mailto']);
1067 else if (preg_match($EMAIL_ADDRESS_PATTERN, $part['mailto'])) {
1069 $out .= html::a(array(
1070 'href' => 'mailto:'.$part['mailto'],
1071 'onclick' => sprintf("return %s.command('compose','%s',this)", JS_OBJECT_NAME, JQ($part['mailto'])),
1072 'title' => $part['mailto'],
1073 'class' => "rcmContactAddress",
1078 $out .= html::span(array('title' => $part['mailto'], 'class' => "rcmContactAddress"), Q($part['name']));
1082 $out .= ' ' . html::a(array(
1084 'onclick' => sprintf("return %s.command('add-contact','%s',this)", JS_OBJECT_NAME, urlencode($part['string'])),
1085 'title' => rcube_label('addtoaddressbook'),
1088 'src' => $CONFIG['skin_path'] . $addicon,
1089 'alt' => "Add contact",
1095 $out .= Q($part['name']);
1096 if ($part['mailto'])
1097 $out .= (strlen($out) ? ' ' : '') . sprintf('<%s>', Q($part['mailto']));
1101 $out .= ','.($max ? ' ' : ' ');
1103 if ($max && $j==$max && $c>$j) {
1114 * Wrap text to a given number of characters per line
1115 * but respect the mail quotation of replies messages (>)
1117 * @param string Text to wrap
1118 * @param int The line width
1119 * @return string The wrapped text
1121 function rcmail_wrap_quoted($text, $max = 76)
1123 // Rebuild the message body with a maximum of $max chars, while keeping quoted message.
1124 $lines = preg_split('/\r?\n/', trim($text));
1127 foreach ($lines as $line) {
1128 if (strlen($line) > $max) {
1129 if (preg_match('/^([>\s]+)/', $line, $regs)) {
1130 $length = strlen($regs[0]);
1131 $prefix = substr($line, 0, $length);
1133 // Remove '> ' from the line, then wordwrap() the line
1134 $line = wordwrap(substr($line, $length), $max - $length);
1136 // Rebuild the line with '> ' at the beginning of each 'subline'
1138 foreach (explode("\n", $line) as $l) {
1139 $newline .= $prefix . $l . "\n";
1142 // Remove the righest newline char
1143 $line = rtrim($newline);
1146 $line = wordwrap($line, $max);
1151 $out .= $line . "\n";
1158 function rcmail_message_part_controls()
1162 $part = asciiwords(get_input_value('_part', RCUBE_INPUT_GPC));
1163 if (!is_object($MESSAGE) || !is_array($MESSAGE->parts) || !($_GET['_uid'] && $_GET['_part']) || !$MESSAGE->mime_parts[$part])
1166 $part = $MESSAGE->mime_parts[$part];
1167 $table = new html_table(array('cols' => 3));
1169 if (!empty($part->filename)) {
1170 $table->add('title', Q(rcube_label('filename')));
1171 $table->add(null, Q($part->filename));
1172 $table->add(null, '[' . html::a('?'.str_replace('_frame=', '_download=', $_SERVER['QUERY_STRING']), Q(rcube_label('download'))) . ']');
1175 if (!empty($part->size)) {
1176 $table->add('title', Q(rcube_label('filesize')));
1177 $table->add(null, Q(show_bytes($part->size)));
1180 return $table->show($attrib);
1185 function rcmail_message_part_frame($attrib)
1189 $part = $MESSAGE->mime_parts[asciiwords(get_input_value('_part', RCUBE_INPUT_GPC))];
1190 $ctype_primary = strtolower($part->ctype_primary);
1192 $attrib['src'] = './?' . str_replace('_frame=', ($ctype_primary=='text' ? '_show=' : '_preload='), $_SERVER['QUERY_STRING']);
1194 return html::iframe($attrib);
1199 * clear message composing settings
1201 function rcmail_compose_cleanup()
1203 if (!isset($_SESSION['compose']))
1206 // remove attachment files from temp dir
1207 if (is_array($_SESSION['compose']['attachments']))
1208 foreach ($_SESSION['compose']['attachments'] as $attachment)
1209 @unlink($attachment['path']);
1211 unset($_SESSION['compose']);
1216 * Send the given message compose object using the configured method
1218 function rcmail_deliver_message(&$message, $from, $mailto)
1220 global $CONFIG, $RCMAIL;
1222 $msg_body = $message->get();
1223 $headers = $message->headers();
1225 // send thru SMTP server using custom SMTP library
1226 if ($CONFIG['smtp_server'])
1228 // generate list of recipients
1229 $a_recipients = array($mailto);
1231 if (strlen($headers['Cc']))
1232 $a_recipients[] = $headers['Cc'];
1233 if (strlen($headers['Bcc']))
1234 $a_recipients[] = $headers['Bcc'];
1236 // clean Bcc from header for recipients
1237 $send_headers = $headers;
1238 unset($send_headers['Bcc']);
1239 // here too, it because txtHeaders() below use $message->_headers not only $send_headers
1240 unset($message->_headers['Bcc']);
1243 $smtp_response = array();
1244 $sent = smtp_mail($from, $a_recipients, ($foo = $message->txtHeaders($send_headers, true)), $msg_body, $smtp_response);
1248 raise_error(array('code' => 800, 'type' => 'smtp', 'line' => __LINE__, 'file' => __FILE__,
1249 'message' => "SMTP error: ".join("\n", $smtp_response)), TRUE, FALSE);
1252 // send mail using PHP's mail() function
1255 // unset some headers because they will be added by the mail() function
1256 $headers_enc = $message->headers($headers);
1257 $headers_php = $message->_headers;
1258 unset($headers_php['To'], $headers_php['Subject']);
1260 // reset stored headers and overwrite
1261 $message->_headers = array();
1262 $header_str = $message->txtHeaders($headers_php);
1264 if (ini_get('safe_mode'))
1265 $sent = mail($headers_enc['To'], $headers_enc['Subject'], $msg_body, $header_str);
1267 $sent = mail($headers_enc['To'], $headers_enc['Subject'], $msg_body, $header_str, "-f$from");
1272 // remove MDN headers after sending
1273 unset($headers['Return-Receipt-To'], $headers['Disposition-Notification-To']);
1275 if ($CONFIG['smtp_log'])
1276 write_log('sendmail', sprintf("User %s [%s]; Message for %s; %s",
1277 $RCMAIL->user->get_username(),
1278 $_SERVER['REMOTE_ADDR'],
1280 !empty($smtp_response) ? join('; ', $smtp_response) : ''));
1283 $message->_headers = array();
1284 $message->headers($headers);
1290 function rcmail_send_mdn($uid)
1292 global $RCMAIL, $IMAP;
1294 $message = new rcube_message($uid);
1296 if ($message->headers->mdn_to && !$message->headers->mdn_sent && $IMAP->check_permflag('MDNSENT'))
1298 $identity = $RCMAIL->user->get_identity();
1299 $sender = format_email_recipient($identity['email'], $identity['name']);
1300 $recipient = array_shift($IMAP->decode_address_list($message->headers->mdn_to));
1301 $mailto = $recipient['mailto'];
1303 $compose = new rcube_mail_mime($RCMAIL->config->header_delimiter());
1304 $compose->setParam(array(
1305 'text_encoding' => 'quoted-printable',
1306 'html_encoding' => 'quoted-printable',
1307 'head_encoding' => 'quoted-printable',
1308 'head_charset' => RCMAIL_CHARSET,
1309 'html_charset' => RCMAIL_CHARSET,
1310 'text_charset' => RCMAIL_CHARSET,
1313 // compose headers array
1315 'Date' => date('r'),
1317 'To' => $message->headers->mdn_to,
1318 'Subject' => rcube_label('receiptread') . ': ' . $message->subject,
1319 'Message-ID' => sprintf('<%s@%s>', md5(uniqid('rcmail'.rand(),true)), $RCMAIL->config->mail_domain($_SESSION['imap_host'])),
1320 'X-Sender' => $identity['email'],
1321 'Content-Type' => 'multipart/report; report-type=disposition-notification',
1324 if ($agent = $RCMAIL->config->get('useragent'))
1325 $headers['User-Agent'] = $agent;
1327 $body = rcube_label("yourmessage") . "\r\n\r\n" .
1328 "\t" . rcube_label("to") . ': ' . rcube_imap::decode_mime_string($message->headers->to, $message->headers->charset) . "\r\n" .
1329 "\t" . rcube_label("subject") . ': ' . $message->subject . "\r\n" .
1330 "\t" . rcube_label("sent") . ': ' . format_date($message->headers->date, $RCMAIL->config->get('date_long')) . "\r\n" .
1331 "\r\n" . rcube_label("receiptnote") . "\r\n";
1333 $ua = $RCMAIL->config->get('useragent', "RoundCube Webmail (Version ".RCMAIL_VERSION.")");
1334 $report = "Reporting-UA: $ua\r\n";
1336 if ($message->headers->to)
1337 $report .= "Original-Recipient: {$message->headers->to}\r\n";
1339 $report .= "Final-Recipient: rfc822; {$identity['email']}\r\n" .
1340 "Original-Message-ID: {$message->headers->messageID}\r\n" .
1341 "Disposition: manual-action/MDN-sent-manually; displayed\r\n";
1343 $compose->headers($headers);
1344 $compose->setTXTBody(wordwrap($body, 75, "\r\n"));
1345 $compose->addAttachment($report, 'message/disposition-notification', 'MDNPart2.txt', false, '7bit', 'inline');
1347 $sent = rcmail_deliver_message($compose, $identity['email'], $mailto);
1351 $IMAP->set_flag($message->uid, 'MDNSENT');
1360 function rcmail_search_filter($attrib)
1364 if (!strlen($attrib['id']))
1365 $attrib['id'] = 'rcmlistfilter';
1367 $attrib['onchange'] = JS_OBJECT_NAME.'.filter_mailbox(this.value)';
1370 RFC3501 (6.4.4): 'ALL', 'RECENT',
1371 'ANSWERED', 'DELETED', 'FLAGGED', 'SEEN',
1372 'UNANSWERED', 'UNDELETED', 'UNFLAGGED', 'UNSEEN',
1373 'NEW', // = (RECENT UNSEEN)
1374 'OLD' // = NOT RECENT
1377 $select_filter = new html_select($attrib);
1378 $select_filter->add(rcube_label('all'), 'ALL');
1379 $select_filter->add(rcube_label('unread'), 'UNSEEN');
1380 $select_filter->add(rcube_label('flagged'), 'FLAGGED');
1381 $select_filter->add(rcube_label('unanswered'), 'UNANSWERED');
1383 $out = $select_filter->show($_SESSION['search_filter']);
1385 $OUTPUT->add_gui_object('search_filter', $attrib['id']);
1390 // register UI objects
1391 $OUTPUT->add_handlers(array(
1392 'mailboxlist' => 'rcmail_mailbox_list',
1393 'messages' => 'rcmail_message_list',
1394 'messagecountdisplay' => 'rcmail_messagecount_display',
1395 'quotadisplay' => 'rcmail_quota_display',
1396 'mailboxname' => 'rcmail_mailbox_name_display',
1397 'messageheaders' => 'rcmail_message_headers',
1398 'messagebody' => 'rcmail_message_body',
1399 'messagecontentframe' => 'rcmail_messagecontent_frame',
1400 'messagepartframe' => 'rcmail_message_part_frame',
1401 'messagepartcontrols' => 'rcmail_message_part_controls',
1402 'searchfilter' => 'rcmail_search_filter',
1403 'searchform' => array($OUTPUT, 'search_form'),