]> git.donarmstrong.com Git - roundcube.git/blob - program/steps/mail/func.inc
Imported Upstream version 0.5.1
[roundcube.git] / program / steps / mail / func.inc
1 <?php
2
3 /*
4  +-----------------------------------------------------------------------+
5  | program/steps/mail/func.inc                                           |
6  |                                                                       |
7  | This file is part of the Roundcube Webmail client                     |
8  | Copyright (C) 2005-2010, Roundcube Dev. - Switzerland                 |
9  | Licensed under the GNU GPL                                            |
10  |                                                                       |
11  | PURPOSE:                                                              |
12  |   Provide webmail functionality and GUI objects                       |
13  |                                                                       |
14  +-----------------------------------------------------------------------+
15  | Author: Thomas Bruederli <roundcube@gmail.com>                        |
16  +-----------------------------------------------------------------------+
17
18  $Id: func.inc 4509 2011-02-09 10:51:50Z thomasb $
19
20 */
21
22 // setup some global vars used by mail steps
23 $SENT_MBOX = $RCMAIL->config->get('sent_mbox');
24 $DRAFTS_MBOX = $RCMAIL->config->get('drafts_mbox');
25 $SEARCH_MODS_DEFAULT = array('*' => array('subject'=>1, 'from'=>1), $SENT_MBOX => array('subject'=>1, 'to'=>1), $DRAFTS_MBOX => array('subject'=>1, 'to'=>1));
26
27 // Simplified for IDN in Unicode
28 //$EMAIL_ADDRESS_PATTERN = '([a-z0-9][a-z0-9\-\.\+\_]*@[a-z0-9][a-z0-9\-\.]*\\.[a-z]{2,5})';
29 $EMAIL_ADDRESS_PATTERN = '([a-z0-9][a-z0-9\-\.\+\_]*@[^&@"\'.][^@&"\']*\\.[a-z]{2,5})';
30
31 // actions that do not require imap connection here
32 $NOIMAP_ACTIONS = array('addcontact', 'autocomplete', 'upload', 'display-attachment', 'remove-attachment', 'get');
33
34 // always instantiate imap object (but not yet connect to server)
35 $RCMAIL->imap_init();
36
37 // log in to imap server
38 if (!in_array($RCMAIL->action, $NOIMAP_ACTIONS) && !$RCMAIL->imap_connect()) {
39   $RCMAIL->kill_session();
40
41   if ($OUTPUT->ajax_call)
42     $OUTPUT->redirect(array(), 2000);
43
44   $OUTPUT->set_env('task', 'login');
45   $OUTPUT->send('login');
46 }
47
48 // set imap properties and session vars
49 if (strlen(trim($mbox = get_input_value('_mbox', RCUBE_INPUT_GPC, true))))
50   $IMAP->set_mailbox(($_SESSION['mbox'] = $mbox));
51 else if ($IMAP)
52   $_SESSION['mbox'] = $IMAP->get_mailbox_name();
53
54 if (!empty($_GET['_page']))
55   $IMAP->set_page(($_SESSION['page'] = intval($_GET['_page'])));
56
57 // set default sort col/order to session
58 if (!isset($_SESSION['sort_col']))
59   $_SESSION['sort_col'] = !empty($CONFIG['message_sort_col']) ? $CONFIG['message_sort_col'] : '';
60 if (!isset($_SESSION['sort_order']))
61   $_SESSION['sort_order'] = strtoupper($CONFIG['message_sort_order']) == 'ASC' ? 'ASC' : 'DESC';
62
63 // set threads mode
64 $a_threading = $RCMAIL->config->get('message_threading', array());
65 if (isset($_GET['_threads'])) {
66   if ($_GET['_threads'])
67     $a_threading[$_SESSION['mbox']] = true;
68   else
69     unset($a_threading[$_SESSION['mbox']]);
70   $RCMAIL->user->save_prefs(array('message_threading' => $a_threading));
71 }
72 $IMAP->set_threading($a_threading[$_SESSION['mbox']]);
73
74 // set message set for search result
75 if (!empty($_REQUEST['_search']) && isset($_SESSION['search'])
76     && $_SESSION['search_request'] == $_REQUEST['_search']
77 ) {
78   $IMAP->set_search_set($_SESSION['search']);
79   $OUTPUT->set_env('search_request', $_REQUEST['_search']);
80   $OUTPUT->set_env('search_text', $_SESSION['last_text_search']);
81 }
82
83 // set main env variables, labels and page title
84 if (empty($RCMAIL->action) || $RCMAIL->action == 'list') {
85   $mbox_name = $IMAP->get_mailbox_name();
86
87   if (empty($RCMAIL->action)) {
88     // initialize searching result if search_filter is used
89     if ($_SESSION['search_filter'] && $_SESSION['search_filter'] != 'ALL') {
90       $search_request = md5($mbox_name.$_SESSION['search_filter']);
91
92       $IMAP->search($mbox_name, $_SESSION['search_filter'], RCMAIL_CHARSET, $_SESSION['sort_col']);
93       $_SESSION['search'] = $IMAP->get_search_set();
94       $_SESSION['search_request'] = $search_request;
95       $OUTPUT->set_env('search_request', $search_request);
96       }
97
98       $search_mods = $RCMAIL->config->get('search_mods', $SEARCH_MODS_DEFAULT);
99       $OUTPUT->set_env('search_mods', $search_mods);
100   }
101
102   // set current mailbox and some other vars in client environment
103   $OUTPUT->set_env('mailbox', $mbox_name);
104   $OUTPUT->set_env('pagesize', $IMAP->page_size);
105   $OUTPUT->set_env('quota', $IMAP->get_capability('QUOTA'));
106   $OUTPUT->set_env('delimiter', $IMAP->get_hierarchy_delimiter());
107   $OUTPUT->set_env('threading', (bool) $IMAP->threading);
108   $OUTPUT->set_env('threads', $IMAP->threading || $IMAP->get_capability('THREAD'));
109
110   if ($CONFIG['flag_for_deletion'])
111     $OUTPUT->set_env('flag_for_deletion', true);
112   if ($CONFIG['read_when_deleted'])
113     $OUTPUT->set_env('read_when_deleted', true);
114   if ($CONFIG['skip_deleted'])
115     $OUTPUT->set_env('skip_deleted', true);
116   if ($CONFIG['display_next'])
117     $OUTPUT->set_env('display_next', true);
118
119   $OUTPUT->set_env('preview_pane_mark_read', $RCMAIL->config->get('preview_pane_mark_read', 0));
120
121   if ($CONFIG['trash_mbox'])
122     $OUTPUT->set_env('trash_mailbox', $CONFIG['trash_mbox']);
123   if ($CONFIG['drafts_mbox'])
124     $OUTPUT->set_env('drafts_mailbox', $CONFIG['drafts_mbox']);
125   if ($CONFIG['junk_mbox'])
126     $OUTPUT->set_env('junk_mailbox', $CONFIG['junk_mbox']);
127
128   if (!$OUTPUT->ajax_call)
129     $OUTPUT->add_label('checkingmail', 'deletemessage', 'movemessagetotrash',
130       'movingmessage', 'copyingmessage', 'deletingmessage', 'markingmessage',
131       'copy', 'move', 'quota');
132
133   $OUTPUT->set_pagetitle(rcmail_localize_foldername($mbox_name));
134 }
135
136
137 /**
138  * return the message list as HTML table
139  */
140 function rcmail_message_list($attrib)
141 {
142   global $IMAP, $CONFIG, $OUTPUT;
143
144   // add some labels to client
145   $OUTPUT->add_label('from', 'to');
146
147   // add id to message list table if not specified
148   if (!strlen($attrib['id']))
149     $attrib['id'] = 'rcubemessagelist';
150
151   // define list of cols to be displayed based on parameter or config
152   if (empty($attrib['columns'])) {
153     $a_show_cols = is_array($CONFIG['list_cols']) ? $CONFIG['list_cols'] : array('subject');
154     $OUTPUT->set_env('col_movable', !in_array('list_cols', (array)$CONFIG['dont_override']));
155   }
156   else {
157     $a_show_cols = preg_split('/[\s,;]+/', strip_quotes($attrib['columns']));
158     $attrib['columns'] = $a_show_cols;
159   }
160
161   // save some variables for use in ajax list
162   $_SESSION['list_attrib'] = $attrib;
163
164   $mbox = $IMAP->get_mailbox_name();
165   $delim = $IMAP->get_hierarchy_delimiter();
166
167   // show 'to' instead of 'from' in sent/draft messages
168   if ((strpos($mbox.$delim, $CONFIG['sent_mbox'].$delim)===0 || strpos($mbox.$delim, $CONFIG['drafts_mbox'].$delim)===0)
169       && (($f = array_search('from', $a_show_cols)) !== false) && array_search('to', $a_show_cols) === false)
170     $a_show_cols[$f] = 'to';
171
172   // make sure 'threads' and 'subject' columns are present
173   if (!in_array('subject', $a_show_cols))
174     array_unshift($a_show_cols, 'subject');
175   if (!in_array('threads', $a_show_cols))
176     array_unshift($a_show_cols, 'threads');
177
178   $skin_path = $_SESSION['skin_path'] = $CONFIG['skin_path'];
179
180   // set client env
181   $OUTPUT->add_gui_object('messagelist', $attrib['id']);
182   $OUTPUT->set_env('autoexpand_threads', intval($CONFIG['autoexpand_threads']));
183   $OUTPUT->set_env('sort_col', $_SESSION['sort_col']);
184   $OUTPUT->set_env('sort_order', $_SESSION['sort_order']);
185   $OUTPUT->set_env('messages', array());
186   $OUTPUT->set_env('coltypes', $a_show_cols);
187
188   $OUTPUT->include_script('list.js');
189
190   $thead = '';
191   foreach (rcmail_message_list_head($attrib, $a_show_cols) as $cell)
192     $thead .= html::tag('td', array('class' => $cell['className'], 'id' => $cell['id']), $cell['html']);
193
194   return html::tag('table',
195     $attrib,
196     html::tag('thead', null, html::tag('tr', null, $thead)) .
197       html::tag('tbody', null, ''),
198         array('style', 'class', 'id', 'cellpadding', 'cellspacing', 'border', 'summary'));
199 }
200
201
202 /**
203  * return javascript commands to add rows to the message list
204  */
205 function rcmail_js_message_list($a_headers, $insert_top=FALSE, $a_show_cols=null)
206 {
207   global $CONFIG, $IMAP, $RCMAIL, $OUTPUT;
208
209   if (empty($a_show_cols)) {
210     if (!empty($_SESSION['list_attrib']['columns']))
211       $a_show_cols = $_SESSION['list_attrib']['columns'];
212     else
213       $a_show_cols = is_array($CONFIG['list_cols']) ? $CONFIG['list_cols'] : array('subject');
214   }
215   else {
216     if (!is_array($a_show_cols))
217       $a_show_cols = preg_split('/[\s,;]+/', strip_quotes($a_show_cols));
218     $head_replace = true;
219   }
220
221   $mbox = $IMAP->get_mailbox_name();
222   $delim = $IMAP->get_hierarchy_delimiter();
223
224   // make sure 'threads' and 'subject' columns are present
225   if (!in_array('subject', $a_show_cols))
226     array_unshift($a_show_cols, 'subject');
227   if (!in_array('threads', $a_show_cols))
228     array_unshift($a_show_cols, 'threads');
229
230   $_SESSION['list_attrib']['columns'] = $a_show_cols;
231
232   // show 'to' instead of 'from' in sent/draft messages
233   if ((strpos($mbox.$delim, $CONFIG['sent_mbox'].$delim)===0 || strpos($mbox.$delim, $CONFIG['drafts_mbox'].$delim)===0)
234       && (($f = array_search('from', $a_show_cols)) !== false) && array_search('to', $a_show_cols) === false)
235     $a_show_cols[$f] = 'to';
236
237   // Make sure there are no duplicated columns (#1486999)
238   $a_show_cols = array_unique($a_show_cols);
239
240   // Plugins may set header's list_cols/list_flags and other rcube_mail_header variables
241   // and list columns
242   $plugin = $RCMAIL->plugins->exec_hook('messages_list',
243     array('messages' => $a_headers, 'cols' => $a_show_cols));
244
245   $a_show_cols = $plugin['cols'];
246   $a_headers   = $plugin['messages'];
247
248   $thead = $head_replace ? rcmail_message_list_head($_SESSION['list_attrib'], $a_show_cols) : NULL;
249
250   $OUTPUT->command('set_message_coltypes', $a_show_cols, $thead);
251
252   if (empty($a_headers))
253     return;
254
255   // remove 'threads', 'attachment', 'flag', 'status' columns, we don't need them here
256   foreach (array('threads', 'attachment', 'flag', 'status') as $col) {
257     if (($key = array_search($col, $a_show_cols)) !== FALSE)
258       unset($a_show_cols[$key]);
259   }
260
261   // loop through message headers
262   foreach ($a_headers as $n => $header) {
263     if (empty($header))
264       continue;
265
266     $a_msg_cols = array();
267     $a_msg_flags = array();
268
269     $IMAP->set_charset(!empty($header->charset) ? $header->charset : $CONFIG['default_charset']);
270
271     // format each col; similar as in rcmail_message_list()
272     foreach ($a_show_cols as $col) {
273       if (in_array($col, array('from', 'to', 'cc', 'replyto')))
274         $cont = Q(rcmail_address_string($header->$col, 3), 'show');
275       else if ($col=='subject') {
276         $cont = trim($IMAP->decode_header($header->$col));
277         if (!$cont) $cont = rcube_label('nosubject');
278         $cont = Q($cont);
279       }
280       else if ($col=='size')
281         $cont = show_bytes($header->$col);
282       else if ($col=='date')
283         $cont = format_date($header->date);
284       else
285         $cont = Q($header->$col);
286
287       $a_msg_cols[$col] = $cont;
288     }
289
290     if ($header->depth)
291       $a_msg_flags['depth'] = $header->depth;
292     else if ($header->has_children)
293       $roots[] = $header->uid;
294     if ($header->parent_uid)
295       $a_msg_flags['parent_uid'] = $header->parent_uid;
296     if ($header->has_children)
297       $a_msg_flags['has_children'] = $header->has_children;
298     if ($header->unread_children)
299       $a_msg_flags['unread_children'] = $header->unread_children;
300     if ($header->deleted)
301       $a_msg_flags['deleted'] = 1;
302     if (!$header->seen)
303       $a_msg_flags['unread'] = 1;
304     if ($header->answered)
305       $a_msg_flags['replied'] = 1;
306     if ($header->forwarded)
307       $a_msg_flags['forwarded'] = 1;
308     if ($header->flagged)
309       $a_msg_flags['flagged'] = 1;
310     if ($header->others['list-post'])
311       $a_msg_flags['ml'] = 1;
312
313     $a_msg_flags['ctype'] = Q($header->ctype);
314     $a_msg_flags['mbox'] = $mbox;
315
316     // merge with plugin result
317     if (!empty($header->list_flags) && is_array($header->list_flags))
318       $a_msg_flags = array_merge($a_msg_flags, $header->list_flags);
319     if (!empty($header->list_cols) && is_array($header->list_cols))
320       $a_msg_cols = array_merge($a_msg_cols, $header->list_cols);
321
322     $OUTPUT->command('add_message_row',
323       $header->uid,
324       $a_msg_cols,
325       $a_msg_flags,
326       $insert_top);
327   }
328
329   if ($IMAP->threading) {
330     $OUTPUT->command('init_threads', (array) $roots);
331   }
332 }
333
334
335 /*
336  * Creates <THEAD> for message list table
337  */
338 function rcmail_message_list_head($attrib, $a_show_cols)
339 {
340   global $CONFIG;
341
342   $skin_path = $_SESSION['skin_path'];
343   $image_tag = html::img(array('src' => "%s%s", 'alt' => "%s"));
344
345   // check to see if we have some settings for sorting
346   $sort_col   = $_SESSION['sort_col'];
347   $sort_order = $_SESSION['sort_order'];
348
349   // define sortable columns
350   $a_sort_cols = array('subject', 'date', 'from', 'to', 'size', 'cc');
351
352   if (!empty($attrib['optionsmenuicon'])) {
353     $onclick = 'return ' . JS_OBJECT_NAME . ".command('menu-open', 'messagelistmenu')";
354     if ($attrib['optionsmenuicon'] === true || $attrib['optionsmenuicon'] == 'true')
355       $list_menu = html::div(array('onclick' => $onclick, 'class' => 'listmenu',
356         'id' => 'listmenulink', 'title' => rcube_label('listoptions')));
357     else
358       $list_menu = html::a(array('href' => '#', 'onclick' => $onclick),
359         html::img(array('src' => $skin_path . $attrib['optionsmenuicon'],
360           'id' => 'listmenulink', 'title' => rcube_label('listoptions')))
361       );
362   }
363   else
364     $list_menu = '';
365
366   $cells = array();
367
368   foreach ($a_show_cols as $col) {
369     // get column name
370     switch ($col) {
371       case 'flag':
372         $col_name = '<span class="flagged">&nbsp;</span>';
373         break;
374       case 'attachment':
375       case 'status':
376         $col_name = '<span class="' . $col .'">&nbsp;</span>';
377         break;
378       case 'threads':
379         $col_name = $list_menu;
380         break;
381       default:
382         $col_name = Q(rcube_label($col));
383     }
384
385     // make sort links
386     if (in_array($col, $a_sort_cols))
387       $col_name = html::a(array('href'=>"./#sort", 'onclick' => 'return '.JS_OBJECT_NAME.".command('sort','".$col."',this)", 'title' => rcube_label('sortby')), $col_name);
388
389     $sort_class = $col == $sort_col ? " sorted$sort_order" : '';
390     $class_name = $col.$sort_class;
391
392     // put it all together
393     $cells[] = array('className' => $class_name, 'id' => "rcm$col", 'html' => $col_name);
394   }
395
396   return $cells;
397 }
398
399
400 /**
401  * return an HTML iframe for loading mail content
402  */
403 function rcmail_messagecontent_frame($attrib)
404   {
405   global $OUTPUT, $RCMAIL;
406
407   if (empty($attrib['id']))
408     $attrib['id'] = 'rcmailcontentwindow';
409
410   $attrib['name'] = $attrib['id'];
411
412   if ($RCMAIL->config->get('preview_pane'))
413     $OUTPUT->set_env('contentframe', $attrib['id']);
414   $OUTPUT->set_env('blankpage', $attrib['src'] ? $OUTPUT->abs_url($attrib['src']) : 'program/blank.gif');
415
416   return html::iframe($attrib);
417   }
418
419
420 function rcmail_messagecount_display($attrib)
421   {
422   global $RCMAIL;
423
424   if (!$attrib['id'])
425     $attrib['id'] = 'rcmcountdisplay';
426
427   $RCMAIL->output->add_gui_object('countdisplay', $attrib['id']);
428
429   $content =  $RCMAIL->action != 'show' ? rcmail_get_messagecount_text() : rcube_label('loading');
430
431   return html::span($attrib, $content);
432   }
433
434
435 function rcmail_get_messagecount_text($count=NULL, $page=NULL)
436   {
437   global $RCMAIL, $IMAP;
438
439   if ($page===NULL)
440     $page = $IMAP->list_page;
441
442   $start_msg = ($page-1) * $IMAP->page_size + 1;
443
444   if ($count!==NULL)
445     $max = $count;
446   else if ($RCMAIL->action)
447     $max = $IMAP->messagecount(NULL, $IMAP->threading ? 'THREADS' : 'ALL');
448
449   if ($max==0)
450     $out = rcube_label('mailboxempty');
451   else
452     $out = rcube_label(array('name' => $IMAP->threading ? 'threadsfromto' : 'messagesfromto',
453             'vars' => array('from'  => $start_msg,
454             'to'    => min($max, $start_msg + $IMAP->page_size - 1),
455             'count' => $max)));
456
457   return Q($out);
458   }
459
460
461 function rcmail_mailbox_name_display($attrib)
462 {
463   global $RCMAIL;
464
465   if (!$attrib['id'])
466     $attrib['id'] = 'rcmmailboxname';
467
468   $RCMAIL->output->add_gui_object('mailboxname', $attrib['id']);
469
470   return html::span($attrib, rcmail_get_mailbox_name_text());
471 }
472
473
474 function rcmail_get_mailbox_name_text()
475 {
476   global $RCMAIL;
477   return rcmail_localize_foldername($RCMAIL->imap->get_mailbox_name());
478 }
479
480
481 function rcmail_send_unread_count($mbox_name, $force=false, $count=null)
482 {
483   global $RCMAIL;
484
485   $old_unseen = rcmail_get_unseen_count($mbox_name);
486
487   if ($count === null)
488     $unseen = $RCMAIL->imap->messagecount($mbox_name, 'UNSEEN', $force);
489   else
490     $unseen = $count;
491
492   if ($unseen != $old_unseen || ($mbox_name == 'INBOX'))
493     $RCMAIL->output->command('set_unread_count', $mbox_name, $unseen, ($mbox_name == 'INBOX'));
494
495   rcmail_set_unseen_count($mbox_name, $unseen);
496
497   return $unseen;
498 }
499
500
501 function rcmail_set_unseen_count($mbox_name, $count)
502 {
503   // @TODO: this data is doubled (session and cache tables) if caching is enabled
504
505   // Make sure we have an array here (#1487066)
506   if (!is_array($_SESSION['unseen_count']))
507     $_SESSION['unseen_count'] = array();
508
509   $_SESSION['unseen_count'][$mbox_name] = $count;
510 }
511
512
513 function rcmail_get_unseen_count($mbox_name)
514 {
515   if (is_array($_SESSION['unseen_count']) && array_key_exists($mbox_name, $_SESSION['unseen_count']))
516     return $_SESSION['unseen_count'][$mbox_name];
517   else
518     return null;
519 }
520
521
522 /**
523  * Sets message is_safe flag according to 'show_images' option value
524  *
525  * @param object rcube_message Message
526  */
527 function rcmail_check_safe(&$message)
528 {
529   global $RCMAIL;
530
531   $show_images = $RCMAIL->config->get('show_images');
532   if (!$message->is_safe
533     && !empty($show_images)
534     && $message->has_html_part())
535   {
536     switch($show_images) {
537       case '1': // known senders only
538         $CONTACTS = new rcube_contacts($RCMAIL->db, $_SESSION['user_id']);
539         if ($CONTACTS->search('email', $message->sender['mailto'], true, false)->count) {
540           $message->set_safe(true);
541         }
542       break;
543       case '2': // always
544         $message->set_safe(true);
545       break;
546     }
547   }
548 }
549
550
551 /**
552  * Cleans up the given message HTML Body (for displaying)
553  *
554  * @param string HTML
555  * @param array  Display parameters 
556  * @param array  CID map replaces (inline images)
557  * @return string Clean HTML
558  */
559 function rcmail_wash_html($html, $p = array(), $cid_replaces)
560 {
561   global $REMOTE_OBJECTS;
562
563   $p += array('safe' => false, 'inline_html' => true);
564
565   // special replacements (not properly handled by washtml class)
566   $html_search = array(
567     '/(<\/nobr>)(\s+)(<nobr>)/i',       // space(s) between <NOBR>
568     '/<title[^>]*>.*<\/title>/i',       // PHP bug #32547 workaround: remove title tag
569     '/^(\0\0\xFE\xFF|\xFF\xFE\0\0|\xFE\xFF|\xFF\xFE|\xEF\xBB\xBF)/',    // byte-order mark (only outlook?)
570     '/<html\s[^>]+>/i',                 // washtml/DOMDocument cannot handle xml namespaces
571   );
572   $html_replace = array(
573     '\\1'.' &nbsp; '.'\\3',
574     '',
575     '',
576     '<html>',
577   );
578   $html = preg_replace($html_search, $html_replace, $html);
579
580   // PCRE errors handling (#1486856), should we use something like for every preg_* use?
581   if ($html === null && ($preg_error = preg_last_error()) != PREG_NO_ERROR) {
582     $errstr = "Could not clean up HTML message! PCRE Error: $preg_error.";
583
584     if ($preg_error == PREG_BACKTRACK_LIMIT_ERROR)
585       $errstr .= " Consider raising pcre.backtrack_limit!";
586     if ($preg_error == PREG_RECURSION_LIMIT_ERROR)
587       $errstr .= " Consider raising pcre.recursion_limit!";
588
589     raise_error(array('code' => 600, 'type' => 'php',
590         'line' => __LINE__, 'file' => __FILE__,
591         'message' => $errstr), true, false);
592     return '';
593   }
594
595   // fix (unknown/malformed) HTML tags before "wash"
596   $html = preg_replace_callback('/(<[\/]*)([^\s>]+)/', 'rcmail_html_tag_callback', $html);
597
598   // charset was converted to UTF-8 in rcube_imap::get_message_part(),
599   // -> change charset specification in HTML accordingly
600   $charset_pattern = '(<meta\s+[^>]*content=)[\'"]?(\w+\/\w+;\s*charset=)([a-z0-9-_]+[\'"]?)';
601   if (preg_match("/$charset_pattern/Ui", $html)) {
602     $html = preg_replace("/$charset_pattern/i", '\\1"\\2'.RCMAIL_CHARSET.'"', $html);
603   }
604   else {
605     // add meta content-type to malformed messages, washtml cannot work without that
606     if (!preg_match('/<head[^>]*>(.*)<\/head>/Uims', $html))
607       $html = '<head></head>'. $html;
608     $html = substr_replace($html, '<meta http-equiv="Content-Type" content="text/html; charset='.RCMAIL_CHARSET.'" />', intval(stripos($html, '<head>')+6), 0);
609   }
610   // turn relative into absolute urls
611   $html = rcmail_resolve_base($html);
612
613   // clean HTML with washhtml by Frederic Motte
614   $wash_opts = array(
615     'show_washed' => false,
616     'allow_remote' => $p['safe'],
617     'blocked_src' => "./program/blocked.gif",
618     'charset' => RCMAIL_CHARSET,
619     'cid_map' => $cid_replaces,
620     'html_elements' => array('body'),
621   );
622
623   if (!$p['inline_html']) {
624     $wash_opts['html_elements'] = array('html','head','title','body');
625   }
626   if ($p['safe']) {
627     $wash_opts['html_elements'][] = 'link';
628     $wash_opts['html_attribs'] = array('rel','type');
629   }
630
631   // overwrite washer options with options from plugins
632   if (isset($p['html_elements']))
633     $wash_opts['html_elements'] = $p['html_elements'];
634   if (isset($p['html_attribs']))
635     $wash_opts['html_attribs'] = $p['html_attribs'];
636
637   // initialize HTML washer
638   $washer = new washtml($wash_opts);
639
640   if (!$p['skip_washer_form_callback'])
641     $washer->add_callback('form', 'rcmail_washtml_callback');
642
643   // allow CSS styles, will be sanitized by rcmail_washtml_callback()
644   if (!$p['skip_washer_style_callback'])
645     $washer->add_callback('style', 'rcmail_washtml_callback');
646
647   $html = $washer->wash($html);
648   $REMOTE_OBJECTS = $washer->extlinks;
649
650   return $html;
651 }
652
653
654 /**
655  * Convert the given message part to proper HTML
656  * which can be displayed the message view
657  *
658  * @param object rcube_message_part Message part
659  * @param array  Display parameters array 
660  * @return string Formatted HTML string
661  */
662 function rcmail_print_body($part, $p = array())
663 {
664   global $RCMAIL;
665
666   // trigger plugin hook
667   $data = $RCMAIL->plugins->exec_hook('message_part_before',
668     array('type' => $part->ctype_secondary, 'body' => $part->body, 'id' => $part->mime_id)
669         + $p + array('safe' => false, 'plain' => false, 'inline_html' => true));
670
671   // convert html to text/plain
672   if ($data['type'] == 'html' && $data['plain']) {
673     $txt = new html2text($data['body'], false, true);
674     $body = $txt->get_text();
675     $part->ctype_secondary = 'plain';
676   }
677   // text/html
678   else if ($data['type'] == 'html') {
679     $body = rcmail_wash_html($data['body'], $data, $part->replaces);
680     $part->ctype_secondary = $data['type'];
681   }
682   // text/enriched
683   else if ($data['type'] == 'enriched') {
684     $part->ctype_secondary = 'html';
685     require_once('lib/enriched.inc');
686     $body = Q(enriched_to_html($data['body']), 'show');
687   }
688   else {
689     // assert plaintext
690     $body = $part->body;
691     $part->ctype_secondary = $data['type'] = 'plain';
692   }
693
694   // free some memory (hopefully)
695   unset($data['body']);
696
697   // plaintext postprocessing
698   if ($part->ctype_secondary == 'plain')
699     $body = rcmail_plain_body($body, $part->ctype_parameters['format'] == 'flowed');
700
701   // allow post-processing of the message body
702   $data = $RCMAIL->plugins->exec_hook('message_part_after',
703     array('type' => $part->ctype_secondary, 'body' => $body, 'id' => $part->mime_id) + $data);
704
705   return $data['type'] == 'html' ? $data['body'] : html::tag('pre', array(), $data['body']);
706 }
707
708
709 /**
710  * Handle links and citation marks in plain text message
711  *
712  * @param string  Plain text string
713  * @param boolean Text uses format=flowed
714  *
715  * @return string Formatted HTML string
716  */
717 function rcmail_plain_body($body, $flowed=false)
718 {
719   global $RCMAIL;
720
721   // make links and email-addresses clickable
722   $replacer = new rcube_string_replacer;
723
724   // search for patterns like links and e-mail addresses
725   $body = preg_replace_callback($replacer->link_pattern, array($replacer, 'link_callback'), $body);
726   $body = preg_replace_callback($replacer->mailto_pattern, array($replacer, 'mailto_callback'), $body);
727
728   // split body into single lines
729   $a_lines = preg_split('/\r?\n/', $body);
730   $quote_level = 0;
731   $last = -1;
732
733   // find/mark quoted lines...
734   for ($n=0, $cnt=count($a_lines); $n < $cnt; $n++) {
735     if ($a_lines[$n][0] == '>' && preg_match('/^(>+\s*)+/', $a_lines[$n], $regs)) {
736       $q = strlen(preg_replace('/\s/', '', $regs[0]));
737       $a_lines[$n] = substr($a_lines[$n], strlen($regs[0]));
738
739       if ($q > $quote_level)
740         $a_lines[$n] = $replacer->get_replacement($replacer->add(
741           str_repeat('<blockquote>', $q - $quote_level))) . $a_lines[$n];
742       else if ($q < $quote_level)
743         $a_lines[$n] = $replacer->get_replacement($replacer->add(
744           str_repeat('</blockquote>', $quote_level - $q))) . $a_lines[$n];
745       else if ($flowed) {
746         // previous line is flowed
747         if (isset($a_lines[$last]) && $a_lines[$n]
748           && $a_lines[$last][strlen($a_lines[$last])-1] == ' ') {
749           // merge lines
750           $a_lines[$last] .= $a_lines[$n];
751           unset($a_lines[$n]);
752         }
753         else
754           $last = $n;
755       }
756     }
757     else {
758       $q = 0;
759       if ($flowed) {
760         // sig separator - line is fixed
761         if ($a_lines[$n] == '-- ') {
762           $last = $n;
763         }
764         else {
765           // remove space-stuffing
766           if ($a_lines[$n][0] == ' ')
767             $a_lines[$n] = substr($a_lines[$n], 1);
768
769           // previous line is flowed?
770           if (isset($a_lines[$last]) && $a_lines[$n]
771             && $a_lines[$last] != '-- '
772             && $a_lines[$last][strlen($a_lines[$last])-1] == ' '
773           ) {
774             $a_lines[$last] .= $a_lines[$n];
775             unset($a_lines[$n]);
776           }
777           else {
778             $last = $n;
779           }
780         }
781         if ($quote_level > 0)
782           $a_lines[$last] = $replacer->get_replacement($replacer->add(
783             str_repeat('</blockquote>', $quote_level))) . $a_lines[$last];
784       }
785       else if ($quote_level > 0)
786         $a_lines[$n] = $replacer->get_replacement($replacer->add(
787           str_repeat('</blockquote>', $quote_level))) . $a_lines[$n];
788     }
789
790     $quote_level = $q;
791   }
792
793   $body = join("\n", $a_lines);
794
795   // quote plain text (don't use Q() here, to display entities "as is")
796   $table = get_html_translation_table(HTML_SPECIALCHARS);
797   unset($table['?']);
798   $body = strtr($body, $table);
799
800   // colorize signature (up to <sig_max_lines> lines)
801   $len = strlen($body);
802   $sig_max_lines = $RCMAIL->config->get('sig_max_lines', 15);
803   while (($sp = strrpos($body, "-- \n", $sp ? -$len+$sp-1 : 0)) !== false) {
804     if ($sp == 0 || $body[$sp-1] == "\n") {
805       // do not touch blocks with more that X lines
806       if (substr_count($body, "\n", $sp) < $sig_max_lines)
807         $body = substr($body, 0, max(0, $sp))
808           .'<span class="sig">'.substr($body, $sp).'</span>';
809       break;
810     }
811   }
812
813   // insert url/mailto links and citation tags
814   $body = $replacer->resolve($body);
815
816   return $body;
817 }
818
819
820 /**
821  * Callback function for washtml cleaning class
822  */
823 function rcmail_washtml_callback($tagname, $attrib, $content)
824 {
825   switch ($tagname) {
826     case 'form':
827       $out = html::div('form', $content);
828       break;
829
830     case 'style':
831       // decode all escaped entities and reduce to ascii strings
832       $stripped = preg_replace('/[^a-zA-Z\(:;]/', '', rcmail_xss_entity_decode($content));
833
834       // now check for evil strings like expression, behavior or url()
835       if (!preg_match('/expression|behavior|url\(|import[^a]/', $stripped)) {
836         $out = html::tag('style', array('type' => 'text/css'), $content);
837         break;
838       }
839
840     default:
841       $out = '';
842   }
843
844   return $out;
845 }
846
847
848 /**
849  * Callback function for HTML tags fixing
850  */
851 function rcmail_html_tag_callback($matches)
852 {
853   $tagname = $matches[2];
854
855   $tagname = preg_replace(array(
856     '/:.*$/',                   // Microsoft's Smart Tags <st1:xxxx>
857     '/[^a-z0-9_\[\]\!-]/i',     // forbidden characters
858     ), '', $tagname);
859
860   return $matches[1].$tagname;
861 }
862
863
864 /**
865  * return table with message headers
866  */
867 function rcmail_message_headers($attrib, $headers=NULL)
868   {
869   global $IMAP, $OUTPUT, $MESSAGE, $PRINT_MODE, $RCMAIL;
870   static $sa_attrib;
871
872   // keep header table attrib
873   if (is_array($attrib) && !$sa_attrib)
874     $sa_attrib = $attrib;
875   else if (!is_array($attrib) && is_array($sa_attrib))
876     $attrib = $sa_attrib;
877
878   if (!isset($MESSAGE))
879     return FALSE;
880
881   // get associative array of headers object
882   if (!$headers)
883     $headers = is_object($MESSAGE->headers) ? get_object_vars($MESSAGE->headers) : $MESSAGE->headers;
884
885   // show these headers
886   $standard_headers = array('subject', 'from', 'to', 'cc', 'bcc', 'replyto',
887     'mail-reply-to', 'mail-followup-to', 'date');
888   $output_headers = array();
889
890   foreach ($standard_headers as $hkey) {
891     if ($headers[$hkey])
892       $value = $headers[$hkey];
893     else if ($headers['others'][$hkey])
894       $value = $headers['others'][$hkey];
895     else
896       continue;
897
898     if ($hkey == 'date') {
899       if ($PRINT_MODE)
900         $header_value = format_date($value, $RCMAIL->config->get('date_long', 'x'));
901       else
902         $header_value = format_date($value);
903     }
904     else if ($hkey == 'replyto') {
905       if ($headers['replyto'] != $headers['from'])
906         $header_value = rcmail_address_string($value, null, true, $attrib['addicon']);
907       else
908         continue;
909     }
910     else if ($hkey == 'mail-reply-to') {
911       if ($headers['mail-replyto'] != $headers['reply-to']
912         && $headers['reply-to'] != $headers['from']
913       )
914         $header_value = rcmail_address_string($value, null, true, $attrib['addicon']);
915       else
916         continue;
917     }
918     else if ($hkey == 'mail-followup-to') {
919       $header_value = rcmail_address_string($value, null, true, $attrib['addicon']);
920     }
921     else if (in_array($hkey, array('from', 'to', 'cc', 'bcc')))
922       $header_value = rcmail_address_string($value, null, true, $attrib['addicon']);
923     else if ($hkey == 'subject' && empty($value))
924       $header_value = rcube_label('nosubject');
925     else
926       $header_value = trim($IMAP->decode_header($value));
927
928     $output_headers[$hkey] = array(
929         'title' => rcube_label(preg_replace('/(^mail-|-)/', '', $hkey)),
930         'value' => $header_value, 'raw' => $value
931     );
932   }
933
934   $plugin = $RCMAIL->plugins->exec_hook('message_headers_output',
935     array('output' => $output_headers, 'headers' => $MESSAGE->headers));
936
937   // compose html table
938   $table = new html_table(array('cols' => 2));
939
940   foreach ($plugin['output'] as $hkey => $row) {
941     $table->add(array('class' => 'header-title'), Q($row['title']));
942     $table->add(array('class' => 'header '.$hkey), Q($row['value'], ($hkey == 'subject' ? 'strict' : 'show')));
943   }
944
945   return $table->show($attrib);
946 }
947
948
949 /**
950  * return block to show full message headers
951  */
952 function rcmail_message_full_headers($attrib, $headers=NULL)
953 {
954   global $OUTPUT;
955   
956   $html = html::div(array('class' => "more-headers show-headers", 'onclick' => "return ".JS_OBJECT_NAME.".command('load-headers','',this)"), '');
957   $html .= html::div(array('id' => "all-headers", 'class' => "all", 'style' => 'display:none'), html::div(array('id' => 'headers-source'), ''));
958   
959   $OUTPUT->add_gui_object('all_headers_row', 'all-headers');
960   $OUTPUT->add_gui_object('all_headers_box', 'headers-source');
961   
962   return html::div($attrib, $html);
963 }
964
965
966 /**
967  * Handler for the 'messagebody' GUI object
968  *
969  * @param array Named parameters
970  * @return string HTML content showing the message body
971  */
972 function rcmail_message_body($attrib)
973   {
974   global $CONFIG, $OUTPUT, $MESSAGE, $IMAP, $RCMAIL, $REMOTE_OBJECTS;
975
976   if (!is_array($MESSAGE->parts) && empty($MESSAGE->body))
977     return '';
978
979   if (!$attrib['id'])
980     $attrib['id'] = 'rcmailMsgBody';
981
982   $safe_mode = $MESSAGE->is_safe || intval($_GET['_safe']);
983   $out = '';
984
985   $header_attrib = array();
986   foreach ($attrib as $attr => $value)
987     if (preg_match('/^headertable([a-z]+)$/i', $attr, $regs))
988       $header_attrib[$regs[1]] = $value;
989
990   if (!empty($MESSAGE->parts))
991     {
992     foreach ($MESSAGE->parts as $i => $part)
993       {
994       if ($part->type == 'headers')
995         $out .= rcmail_message_headers(sizeof($header_attrib) ? $header_attrib : NULL, $part->headers);
996       else if ($part->type == 'content' && $part->size)
997         {
998         if (empty($part->ctype_parameters) || empty($part->ctype_parameters['charset']))
999           $part->ctype_parameters['charset'] = $MESSAGE->headers->charset;
1000
1001         // fetch part if not available
1002         if (!isset($part->body))
1003           $part->body = $MESSAGE->get_part_content($part->mime_id);
1004
1005         // message is cached but not exists (#1485443), or other error
1006         if ($part->body === false) {
1007           rcmail_message_error($MESSAGE->uid);
1008         }
1009
1010         $plugin = $RCMAIL->plugins->exec_hook('message_body_prefix', array(
1011           'part' => $part, 'prefix' => ''));
1012
1013         $body = rcmail_print_body($part, array('safe' => $safe_mode, 'plain' => !$CONFIG['prefer_html']));
1014
1015         if ($part->ctype_secondary == 'html') {
1016           $body = rcmail_html4inline($body, $attrib['id'], 'rcmBody', $attrs);
1017           $div_attr = array('class' => 'message-htmlpart');
1018           $style = array();
1019
1020           if (!empty($attrs)) {
1021             foreach ($attrs as $a_idx => $a_val)
1022               $style[] = $a_idx . ': ' . $a_val;
1023             if (!empty($style))
1024               $div_attr['style'] = implode('; ', $style);
1025           }
1026
1027           $out .= html::div($div_attr, $plugin['prefix'] . $body);
1028         }
1029         else
1030           $out .= html::div('message-part', $plugin['prefix'] . $body);
1031         }
1032       }
1033     }
1034   else {
1035     $plugin = $RCMAIL->plugins->exec_hook('message_body_prefix', array(
1036       'part' => $MESSAGE, 'prefix' => ''));
1037
1038     $out .= html::div('message-part', $plugin['prefix'] . html::tag('pre', array(),
1039       rcmail_plain_body(Q($MESSAGE->body, 'strict', false))));
1040     }
1041
1042   $ctype_primary = strtolower($MESSAGE->structure->ctype_primary);
1043   $ctype_secondary = strtolower($MESSAGE->structure->ctype_secondary);
1044
1045   // list images after mail body
1046   if ($CONFIG['inline_images']
1047       && $ctype_primary == 'multipart'
1048       && !empty($MESSAGE->attachments))
1049     {
1050     foreach ($MESSAGE->attachments as $attach_prop) {
1051       // Content-Type: image/*...
1052       if (preg_match('/^image\//i', $attach_prop->mimetype) ||
1053         // ...or known file extension: many clients are using application/octet-stream
1054         ($attach_prop->filename &&
1055           preg_match('/^application\/octet-stream$/i', $attach_prop->mimetype) &&
1056           preg_match('/\.(jpg|jpeg|png|gif|bmp)$/i', $attach_prop->filename))
1057       ) {
1058         $out .= html::tag('hr') . html::p(array('align' => "center"),
1059           html::img(array(
1060             'src' => $MESSAGE->get_part_url($attach_prop->mime_id),
1061             'title' => $attach_prop->filename,
1062             'alt' => $attach_prop->filename,
1063           )));
1064         }
1065     }
1066   }
1067
1068   // tell client that there are blocked remote objects
1069   if ($REMOTE_OBJECTS && !$safe_mode)
1070     $OUTPUT->set_env('blockedobjects', true);
1071
1072   return html::div($attrib, $out);
1073   }
1074
1075
1076 /**
1077  * Convert all relative URLs according to a <base> in HTML
1078  */
1079 function rcmail_resolve_base($body)
1080 {
1081   // check for <base href=...>
1082   if (preg_match('!(<base.*href=["\']?)([hftps]{3,5}://[a-z0-9/.%-]+)!i', $body, $regs)) {
1083     $replacer = new rcube_base_replacer($regs[2]);
1084
1085     // replace all relative paths
1086     $body = preg_replace_callback('/(src|background|href)=(["\']?)([\.\/]+[^"\'\s]+)(\2|\s|>)/Ui', array($replacer, 'callback'), $body);
1087     $body = preg_replace_callback('/(url\s*\()(["\']?)([\.\/]+[^"\'\)\s]+)(\2)\)/Ui', array($replacer, 'callback'), $body);
1088   }
1089
1090   return $body;
1091 }
1092
1093 /**
1094  * modify a HTML message that it can be displayed inside a HTML page
1095  */
1096 function rcmail_html4inline($body, $container_id, $body_id='', &$attributes=null)
1097 {
1098   $last_style_pos = 0;
1099   $body_lc = strtolower($body);
1100   $cont_id = $container_id.($body_id ? ' div.'.$body_id : '');
1101
1102   // find STYLE tags
1103   while (($pos = strpos($body_lc, '<style', $last_style_pos)) && ($pos2 = strpos($body_lc, '</style>', $pos)))
1104   {
1105     $pos = strpos($body_lc, '>', $pos)+1;
1106
1107     // replace all css definitions with #container [def]
1108     $styles = rcmail_mod_css_styles(
1109       substr($body, $pos, $pos2-$pos), $cont_id);
1110
1111     $body = substr($body, 0, $pos) . $styles . substr($body, $pos2);
1112     $body_lc = strtolower($body);
1113     $last_style_pos = $pos2;
1114   }
1115
1116   // modify HTML links to open a new window if clicked
1117   $GLOBALS['rcmail_html_container_id'] = $container_id;
1118   $body = preg_replace_callback('/<(a|link)\s+([^>]+)>/Ui', 'rcmail_alter_html_link', $body);
1119   unset($GLOBALS['rcmail_html_container_id']);
1120
1121   $body = preg_replace(array(
1122       // add comments arround html and other tags
1123       '/(<!DOCTYPE[^>]*>)/i',
1124       '/(<\?xml[^>]*>)/i',
1125       '/(<\/?html[^>]*>)/i',
1126       '/(<\/?head[^>]*>)/i',
1127       '/(<title[^>]*>.*<\/title>)/Ui',
1128       '/(<\/?meta[^>]*>)/i',
1129       // quote <? of php and xml files that are specified as text/html
1130       '/<\?/',
1131       '/\?>/',
1132       // replace <body> with <div>
1133       '/<body([^>]*)>/i',
1134       '/<\/body>/i',
1135       ),
1136     array(
1137       '<!--\\1-->',
1138       '<!--\\1-->',
1139       '<!--\\1-->',
1140       '<!--\\1-->',
1141       '<!--\\1-->',
1142       '<!--\\1-->',
1143       '&lt;?',
1144       '?&gt;',
1145       '<div class="'.$body_id.'"\\1>',
1146       '</div>',
1147       ),
1148     $body);
1149
1150   $attributes = array();
1151
1152   // Handle body attributes that doesn't play nicely with div elements
1153   $regexp = '/<div class="' . preg_quote($body_id, '/') . '"([^>]*)/';
1154   if (preg_match($regexp, $body, $m)) {
1155     $attrs = $m[0];
1156     // Get bgcolor, we'll set it as background-color of the message container
1157     if ($m[1] && preg_match('/bgcolor=["\']*([a-z0-9#]+)["\']*/', $attrs, $mb)) {
1158       $attributes['background-color'] = $mb[1];
1159       $attrs = preg_replace('/bgcolor=["\']*([a-z0-9#]+)["\']*/', '', $attrs);
1160     }
1161     // Get background, we'll set it as background-image of the message container
1162     if ($m[1] && preg_match('/background=["\']*([^"\'>\s]+)["\']*/', $attrs, $mb)) {
1163       $attributes['background-image'] = 'url('.$mb[1].')';
1164       $attrs = preg_replace('/background=["\']*([^"\'>\s]+)["\']*/', '', $attrs);
1165     }
1166     if (!empty($attributes)) {
1167       $body = preg_replace($regexp, rtrim($attrs), $body, 1);
1168     }
1169
1170     // handle body styles related to background image
1171     if ($attributes['background-image']) {
1172       // get body style
1173       if (preg_match('/#'.preg_quote($cont_id, '/').'\s+\{([^}]+)}/i', $body, $m)) {
1174         // get background related style
1175         if (preg_match_all('/(background-position|background-repeat)\s*:\s*([^;]+);/i', $m[1], $ma, PREG_SET_ORDER)) {
1176           foreach ($ma as $style)
1177             $attributes[$style[1]] = $style[2];
1178         }
1179       }
1180     }
1181   }
1182   // make sure there's 'rcmBody' div, we need it for proper css modification
1183   // its name is hardcoded in rcmail_message_body() also
1184   else {
1185     $body = '<div class="' . $body_id . '">' . $body . '</div>';
1186   }
1187
1188   return $body;
1189 }
1190
1191
1192 /**
1193  * parse link attributes and set correct target
1194  */
1195 function rcmail_alter_html_link($matches)
1196 {
1197   global $RCMAIL, $EMAIL_ADDRESS_PATTERN;
1198
1199   $tag = $matches[1];
1200   $attrib = parse_attrib_string($matches[2]);
1201   $end = '>';
1202
1203   if ($tag == 'link' && preg_match('/^https?:\/\//i', $attrib['href'])) {
1204     $tempurl = 'tmp-' . md5($attrib['href']) . '.css';
1205     $_SESSION['modcssurls'][$tempurl] = $attrib['href'];
1206     $attrib['href'] = $RCMAIL->url(array('task' => 'utils', 'action' => 'modcss', 'u' => $tempurl, 'c' => $GLOBALS['rcmail_html_container_id']));
1207     $end = ' />';
1208   }
1209   else if (preg_match('/^mailto:'.$EMAIL_ADDRESS_PATTERN.'(\?[^"\'>]+)?/i', $attrib['href'], $mailto)) {
1210     $attrib['href'] = $mailto[0];
1211     $attrib['onclick'] = sprintf(
1212       "return %s.command('compose','%s',this)",
1213       JS_OBJECT_NAME,
1214       JQ($mailto[1].$mailto[2]));
1215   }
1216   else if (!empty($attrib['href']) && $attrib['href'][0] != '#') {
1217     $attrib['target'] = '_blank';
1218   }
1219
1220   return "<$tag" . html::attrib_string($attrib, array('href','name','target','onclick','id','class','style','title','rel','type','media')) . $end;
1221 }
1222
1223
1224 /**
1225  * decode address string and re-format it as HTML links
1226  */
1227 function rcmail_address_string($input, $max=null, $linked=false, $addicon=null)
1228 {
1229   global $IMAP, $RCMAIL, $PRINT_MODE, $CONFIG;
1230   static $got_writable_abook = null;
1231
1232   $a_parts = $IMAP->decode_address_list($input);
1233
1234   if (!sizeof($a_parts))
1235     return $input;
1236
1237   $c = count($a_parts);
1238   $j = 0;
1239   $out = '';
1240
1241   if ($got_writable_abook === null && $books = $RCMAIL->get_address_sources(true)) {
1242     $got_writable_abook = true;
1243   }
1244
1245   foreach ($a_parts as $part) {
1246     $j++;
1247
1248     $name   = $part['name'];
1249     $mailto = $part['mailto'];
1250     $string = $part['string'];
1251
1252     // IDNA ASCII to Unicode
1253     if ($name == $mailto)
1254       $name = rcube_idn_to_utf8($name);
1255     if ($string == $mailto)
1256       $string = rcube_idn_to_utf8($string);
1257     $mailto = rcube_idn_to_utf8($mailto);
1258
1259     if ($PRINT_MODE) {
1260       $out .= sprintf('%s &lt;%s&gt;', Q($name), $mailto);
1261     }
1262     else if (check_email($part['mailto'], false)) {
1263       if ($linked) {
1264         $out .= html::a(array(
1265             'href' => 'mailto:'.$mailto,
1266             'onclick' => sprintf("return %s.command('compose','%s',this)", JS_OBJECT_NAME, JQ($mailto)),
1267             'title' => $mailto,
1268             'class' => "rcmContactAddress",
1269           ),
1270         Q($name ? $name : $mailto));
1271       }
1272       else {
1273         $out .= html::span(array('title' => $mailto, 'class' => "rcmContactAddress"),
1274           Q($name ? $name : $mailto));
1275       }
1276
1277       if ($addicon && $got_writable_abook) {
1278         $out .= '&nbsp;' . html::a(array(
1279             'href' => "#add",
1280             'onclick' => sprintf("return %s.command('add-contact','%s',this)", JS_OBJECT_NAME, urlencode($string)),
1281             'title' => rcube_label('addtoaddressbook'),
1282           ),
1283           html::img(array(
1284             'src' => $CONFIG['skin_path'] . $addicon,
1285             'alt' => "Add contact",
1286           )));
1287       }
1288     }
1289     else {
1290       if ($name)
1291         $out .= Q($name);
1292       if ($mailto)
1293         $out .= (strlen($out) ? ' ' : '') . sprintf('&lt;%s&gt;', Q($mailto));
1294     }
1295
1296     if ($c>$j)
1297       $out .= ','.($max ? '&nbsp;' : ' ');
1298
1299     if ($max && $j==$max && $c>$j) {
1300       $out .= '...';
1301       break;
1302     }
1303   }
1304
1305   return $out;
1306 }
1307
1308
1309 /**
1310  * Wrap text to a given number of characters per line
1311  * but respect the mail quotation of replies messages (>).
1312  * Finally add another quotation level by prpending the lines
1313  * with >
1314  *
1315  * @param string Text to wrap
1316  * @param int The line width
1317  * @return string The wrapped text
1318  */
1319 function rcmail_wrap_and_quote($text, $length = 72)
1320 {
1321   // Rebuild the message body with a maximum of $max chars, while keeping quoted message.
1322   $max = min(77, $length + 8);
1323   $lines = preg_split('/\r?\n/', trim($text));
1324   $out = '';
1325
1326   foreach ($lines as $line) {
1327     // don't wrap already quoted lines
1328     if ($line[0] == '>')
1329       $line = '>' . rtrim($line);
1330     else if (mb_strlen($line) > $max) {
1331       $newline = '';
1332       foreach(explode("\n", rc_wordwrap($line, $length - 2)) as $l) {
1333         if (strlen($l))
1334           $newline .= '> ' . $l . "\n";
1335         else
1336           $newline .= ">\n";
1337       }
1338       $line = rtrim($newline);
1339     }
1340     else
1341       $line = '> ' . $line;
1342
1343     // Append the line
1344     $out .= $line . "\n";
1345   }
1346
1347   return $out;
1348 }
1349
1350
1351 function rcmail_draftinfo_encode($p)
1352 {
1353   $parts = array();
1354   foreach ($p as $key => $val)
1355     $parts[] = $key . '=' . ($key == 'folder' ? base64_encode($val) : $val);
1356
1357   return join('; ', $parts);
1358 }
1359
1360
1361 function rcmail_draftinfo_decode($str)
1362 {
1363   $info = array();
1364   foreach (preg_split('/;\s+/', $str) as $part) {
1365     list($key, $val) = explode('=', $part, 2);
1366     if ($key == 'folder')
1367       $val = base64_decode($val);
1368     $info[$key] = $val;
1369   }
1370
1371   return $info;
1372 }
1373
1374
1375 function rcmail_message_part_controls()
1376 {
1377   global $MESSAGE;
1378
1379   $part = asciiwords(get_input_value('_part', RCUBE_INPUT_GPC));
1380   if (!is_object($MESSAGE) || !is_array($MESSAGE->parts) || !($_GET['_uid'] && $_GET['_part']) || !$MESSAGE->mime_parts[$part])
1381     return '';
1382
1383   $part = $MESSAGE->mime_parts[$part];
1384   $table = new html_table(array('cols' => 3));
1385
1386   if (!empty($part->filename)) {
1387     $table->add('title', Q(rcube_label('filename')));
1388     $table->add(null, Q($part->filename));
1389     $table->add(null, '[' . html::a('?'.str_replace('_frame=', '_download=', $_SERVER['QUERY_STRING']), Q(rcube_label('download'))) . ']');
1390   }
1391
1392   if (!empty($part->size)) {
1393     $table->add('title', Q(rcube_label('filesize')));
1394     $table->add(null, Q(show_bytes($part->size)));
1395   }
1396
1397   return $table->show($attrib);
1398 }
1399
1400
1401
1402 function rcmail_message_part_frame($attrib)
1403 {
1404   global $MESSAGE;
1405
1406   $part = $MESSAGE->mime_parts[asciiwords(get_input_value('_part', RCUBE_INPUT_GPC))];
1407   $ctype_primary = strtolower($part->ctype_primary);
1408
1409   $attrib['src'] = './?' . str_replace('_frame=', ($ctype_primary=='text' ? '_show=' : '_preload='), $_SERVER['QUERY_STRING']);
1410
1411   return html::iframe($attrib);
1412 }
1413
1414
1415 /**
1416  * clear message composing settings
1417  */
1418 function rcmail_compose_cleanup()
1419 {
1420   if (!isset($_SESSION['compose']))
1421     return;
1422
1423   $rcmail = rcmail::get_instance();
1424   $rcmail->plugins->exec_hook('attachments_cleanup', array());
1425   $rcmail->session->remove('compose');
1426 }
1427
1428
1429 /**
1430  * Send the given message using the configured method
1431  *
1432  * @param object $message    Reference to Mail_MIME object
1433  * @param string $from       Sender address string
1434  * @param array  $mailto     Array of recipient address strings
1435  * @param array  $smtp_error SMTP error array (reference)
1436  * @param string $body_file  Location of file with saved message body (reference)
1437  * @param array  $smtp_opts  SMTP options (e.g. DSN request)
1438  *
1439  * @return boolean Send status.
1440  */
1441 function rcmail_deliver_message(&$message, $from, $mailto, &$smtp_error, &$body_file, $smtp_opts=null)
1442 {
1443   global $CONFIG, $RCMAIL;
1444
1445   $headers = $message->headers();
1446
1447   // send thru SMTP server using custom SMTP library
1448   if ($CONFIG['smtp_server']) {
1449     // generate list of recipients
1450     $a_recipients = array($mailto);
1451
1452     if (strlen($headers['Cc']))
1453       $a_recipients[] = $headers['Cc'];
1454     if (strlen($headers['Bcc']))
1455       $a_recipients[] = $headers['Bcc'];
1456
1457     // clean Bcc from header for recipients
1458     $send_headers = $headers;
1459     unset($send_headers['Bcc']);
1460     // here too, it because txtHeaders() below use $message->_headers not only $send_headers
1461     unset($message->_headers['Bcc']);
1462
1463     $smtp_headers = $message->txtHeaders($send_headers, true);
1464
1465     if ($message->getParam('delay_file_io')) {
1466       // use common temp dir
1467       $temp_dir = $RCMAIL->config->get('temp_dir');
1468       $body_file = tempnam($temp_dir, 'rcmMsg');
1469       if (PEAR::isError($mime_result = $message->saveMessageBody($body_file))) {
1470         raise_error(array('code' => 600, 'type' => 'php',
1471             'file' => __FILE__, 'line' => __LINE__,
1472             'message' => "Could not create message: ".$mime_result->getMessage()),
1473             TRUE, FALSE);
1474         return false;
1475       }
1476       $msg_body = fopen($body_file, 'r');
1477     } else {
1478       $msg_body = $message->get();
1479     }
1480
1481     // send message
1482     if (!is_object($RCMAIL->smtp))
1483       $RCMAIL->smtp_init(true);
1484
1485     $sent = $RCMAIL->smtp->send_mail($from, $a_recipients, $smtp_headers, $msg_body, $smtp_opts);
1486     $smtp_response = $RCMAIL->smtp->get_response();
1487     $smtp_error = $RCMAIL->smtp->get_error();
1488
1489     // log error
1490     if (!$sent)
1491       raise_error(array('code' => 800, 'type' => 'smtp', 'line' => __LINE__, 'file' => __FILE__,
1492                         'message' => "SMTP error: ".join("\n", $smtp_response)), TRUE, FALSE);
1493   }
1494   // send mail using PHP's mail() function
1495   else {
1496     // unset some headers because they will be added by the mail() function
1497     $headers_enc = $message->headers($headers);
1498     $headers_php = $message->_headers;
1499     unset($headers_php['To'], $headers_php['Subject']);
1500
1501     // reset stored headers and overwrite
1502     $message->_headers = array();
1503     $header_str = $message->txtHeaders($headers_php);
1504
1505     // #1485779
1506     if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
1507       if (preg_match_all('/<([^@]+@[^>]+)>/', $headers_enc['To'], $m)) {
1508         $headers_enc['To'] = implode(', ', $m[1]);
1509       }
1510     }
1511
1512     $msg_body = $message->get();
1513
1514     if (PEAR::isError($msg_body))
1515       raise_error(array('code' => 600, 'type' => 'php',
1516             'file' => __FILE__, 'line' => __LINE__,
1517             'message' => "Could not create message: ".$msg_body->getMessage()),
1518             TRUE, FALSE);
1519     else {
1520       $delim   = $RCMAIL->config->header_delimiter();
1521       $to      = $headers_enc['To'];
1522       $subject = $headers_enc['Subject'];
1523       $header_str = rtrim($header_str);
1524
1525       if ($delim != "\r\n") {
1526         $header_str = str_replace("\r\n", $delim, $header_str);
1527         $msg_body   = str_replace("\r\n", $delim, $msg_body);
1528         $to         = str_replace("\r\n", $delim, $to);
1529         $subject    = str_replace("\r\n", $delim, $subject);
1530       }
1531
1532       if (ini_get('safe_mode'))
1533         $sent = mail($to, $subject, $msg_body, $header_str);
1534       else
1535         $sent = mail($to, $subject, $msg_body, $header_str, "-f$from");
1536     }
1537   }
1538
1539   if ($sent) {
1540     $RCMAIL->plugins->exec_hook('message_sent', array('headers' => $headers, 'body' => $msg_body));
1541
1542     // remove MDN headers after sending
1543     unset($headers['Return-Receipt-To'], $headers['Disposition-Notification-To']);
1544
1545     // get all recipients
1546     if ($headers['Cc'])
1547       $mailto .= $headers['Cc'];
1548     if ($headers['Bcc'])
1549       $mailto .= $headers['Bcc'];
1550     if (preg_match_all('/<([^@]+@[^>]+)>/', $mailto, $m))
1551       $mailto = implode(', ', array_unique($m[1]));
1552
1553     if ($CONFIG['smtp_log']) {
1554       write_log('sendmail', sprintf("User %s [%s]; Message for %s; %s",
1555         $RCMAIL->user->get_username(),
1556         $_SERVER['REMOTE_ADDR'],
1557         $mailto,
1558         !empty($smtp_response) ? join('; ', $smtp_response) : ''));
1559     }
1560   }
1561
1562   if (is_resource($msg_body)) {
1563     fclose($msg_body);
1564   }
1565
1566   $message->_headers = array();
1567   $message->headers($headers);
1568
1569   return $sent;
1570 }
1571
1572 /**
1573  * Send the MDN response
1574  *
1575  * @param mixed $message    Original message object (rcube_message) or UID
1576  * @param array $smtp_error SMTP error array (reference)
1577  *
1578  * @return boolean Send status
1579  */
1580 function rcmail_send_mdn($message, &$smtp_error)
1581 {
1582   global $RCMAIL, $IMAP;
1583
1584   if (!is_a($message, rcube_message))
1585     $message = new rcube_message($message);
1586
1587   if ($message->headers->mdn_to && !$message->headers->mdn_sent &&
1588     ($IMAP->check_permflag('MDNSENT') || $IMAP->check_permflag('*')))
1589   {
1590     $identity = $RCMAIL->user->get_identity();
1591     $sender = format_email_recipient($identity['email'], $identity['name']);
1592     $recipient = array_shift($IMAP->decode_address_list($message->headers->mdn_to));
1593     $mailto = $recipient['mailto'];
1594
1595     $compose = new Mail_mime("\r\n");
1596
1597     $compose->setParam('text_encoding', 'quoted-printable');
1598     $compose->setParam('html_encoding', 'quoted-printable');
1599     $compose->setParam('head_encoding', 'quoted-printable');
1600     $compose->setParam('head_charset', RCMAIL_CHARSET);
1601     $compose->setParam('html_charset', RCMAIL_CHARSET);
1602     $compose->setParam('text_charset', RCMAIL_CHARSET);
1603
1604     // compose headers array
1605     $headers = array(
1606       'Date' => rcmail_user_date(),
1607       'From' => $sender,
1608       'To'   => $message->headers->mdn_to,
1609       'Subject' => rcube_label('receiptread') . ': ' . $message->subject,
1610       'Message-ID' => rcmail_gen_message_id(),
1611       'X-Sender' => $identity['email'],
1612       'References' => trim($message->headers->references . ' ' . $message->headers->messageID),
1613     );
1614
1615     if ($agent = $RCMAIL->config->get('useragent'))
1616       $headers['User-Agent'] = $agent;
1617
1618     $body = rcube_label("yourmessage") . "\r\n\r\n" .
1619       "\t" . rcube_label("to") . ': ' . rcube_imap::decode_mime_string($message->headers->to, $message->headers->charset) . "\r\n" .
1620       "\t" . rcube_label("subject") . ': ' . $message->subject . "\r\n" .
1621       "\t" . rcube_label("sent") . ': ' . format_date($message->headers->date, $RCMAIL->config->get('date_long')) . "\r\n" .
1622       "\r\n" . rcube_label("receiptnote") . "\r\n";
1623
1624     $ua = $RCMAIL->config->get('useragent', "Roundcube Webmail (Version ".RCMAIL_VERSION.")");
1625     $report = "Reporting-UA: $ua\r\n";
1626
1627     if ($message->headers->to)
1628         $report .= "Original-Recipient: {$message->headers->to}\r\n";
1629
1630     $report .= "Final-Recipient: rfc822; {$identity['email']}\r\n" .
1631                "Original-Message-ID: {$message->headers->messageID}\r\n" .
1632                "Disposition: manual-action/MDN-sent-manually; displayed\r\n";
1633
1634     $compose->headers($headers);
1635     $compose->setContentType('multipart/report', array('report-type'=> 'disposition-notification'));
1636     $compose->setTXTBody(rc_wordwrap($body, 75, "\r\n"));
1637     $compose->addAttachment($report, 'message/disposition-notification', 'MDNPart2.txt', false, '7bit', 'inline');
1638
1639     $sent = rcmail_deliver_message($compose, $identity['email'], $mailto, $smtp_error, $body_file);
1640
1641     if ($sent)
1642     {
1643       $IMAP->set_flag($message->uid, 'MDNSENT');
1644       return true;
1645     }
1646   }
1647
1648   return false;
1649 }
1650
1651 // Returns unique Message-ID
1652 function rcmail_gen_message_id()
1653 {
1654   global $RCMAIL;
1655
1656   $local_part  = md5(uniqid('rcmail'.mt_rand(),true));
1657   $domain_part = $RCMAIL->user->get_username('domain');
1658
1659   // Try to find FQDN, some spamfilters doesn't like 'localhost' (#1486924)
1660   if (!preg_match('/\.[a-z]+$/i', $domain_part)) {
1661     if (($host = preg_replace('/:[0-9]+$/', '', $_SERVER['HTTP_HOST']))
1662       && preg_match('/\.[a-z]+$/i', $host)) {
1663         $domain_part = $host;
1664     }
1665     else if (($host = preg_replace('/:[0-9]+$/', '', $_SERVER['SERVER_NAME']))
1666       && preg_match('/\.[a-z]+$/i', $host)) {
1667         $domain_part = $host;
1668     }
1669   }
1670
1671   return sprintf('<%s@%s>', $local_part, $domain_part);
1672 }
1673
1674 // Returns RFC2822 formatted current date in user's timezone
1675 function rcmail_user_date()
1676 {
1677   global $CONFIG;
1678
1679   // get user's timezone
1680   if ($CONFIG['timezone'] === 'auto') {
1681     $tz = isset($_SESSION['timezone']) ? $_SESSION['timezone'] : date('Z')/3600;
1682   }
1683   else {
1684     $tz = $CONFIG['timezone'];
1685     if ($CONFIG['dst_active'])
1686       $tz++;
1687   }
1688
1689   $date = time() + $tz * 60 * 60;
1690   $date = gmdate('r', $date);
1691   $tz   = sprintf('%+05d', intval($tz) * 100 + ($tz - intval($tz)) * 60);
1692   $date = preg_replace('/[+-][0-9]{4}$/', $tz, $date);
1693
1694   return $date;
1695 }
1696
1697 // Fixes some content-type names
1698 function rcmail_fix_mimetype($name)
1699 {
1700   // Some versions of Outlook create garbage Content-Type:
1701   // application/pdf.A520491B_3BF7_494D_8855_7FAC2C6C0608
1702   if (preg_match('/^application\/pdf.+/', $name))
1703     $name = 'application/pdf';
1704
1705   return $name;
1706 }
1707
1708 function rcmail_search_filter($attrib)
1709 {
1710   global $OUTPUT, $CONFIG;
1711
1712   if (!strlen($attrib['id']))
1713     $attrib['id'] = 'rcmlistfilter';
1714
1715   $attrib['onchange'] = JS_OBJECT_NAME.'.filter_mailbox(this.value)';
1716
1717   /*
1718     RFC3501 (6.4.4): 'ALL', 'RECENT', 
1719     'ANSWERED', 'DELETED', 'FLAGGED', 'SEEN',
1720     'UNANSWERED', 'UNDELETED', 'UNFLAGGED', 'UNSEEN',
1721     'NEW', // = (RECENT UNSEEN)
1722     'OLD' // = NOT RECENT
1723   */
1724
1725   $select_filter = new html_select($attrib);
1726   $select_filter->add(rcube_label('all'), 'ALL');
1727   $select_filter->add(rcube_label('unread'), 'UNSEEN');
1728   $select_filter->add(rcube_label('flagged'), 'FLAGGED');
1729   $select_filter->add(rcube_label('unanswered'), 'UNANSWERED');
1730   if (!$CONFIG['skip_deleted'])
1731     $select_filter->add(rcube_label('deleted'), 'DELETED');
1732
1733   $out = $select_filter->show($_SESSION['search_filter']);
1734
1735   $OUTPUT->add_gui_object('search_filter', $attrib['id']);
1736
1737   return $out;
1738 }
1739
1740 function rcmail_message_error($uid=null)
1741 {
1742   global $RCMAIL;
1743
1744   // Set env variables for messageerror.html template
1745   if ($RCMAIL->action == 'show') {
1746     $mbox_name = $RCMAIL->imap->get_mailbox_name();
1747     $RCMAIL->output->set_env('mailbox', $mbox_name);
1748     $RCMAIL->output->set_env('uid', null);
1749   }
1750   // display error message
1751   $RCMAIL->output->show_message('messageopenerror', 'error');
1752   // ... display message error page
1753   $RCMAIL->output->send('messageerror');
1754 }
1755
1756 // register UI objects
1757 $OUTPUT->add_handlers(array(
1758   'mailboxlist' => 'rcmail_mailbox_list',
1759   'messages' => 'rcmail_message_list',
1760   'messagecountdisplay' => 'rcmail_messagecount_display',
1761   'quotadisplay' => 'rcmail_quota_display',
1762   'mailboxname' => 'rcmail_mailbox_name_display',
1763   'messageheaders' => 'rcmail_message_headers',
1764   'messagefullheaders' => 'rcmail_message_full_headers',
1765   'messagebody' => 'rcmail_message_body',
1766   'messagecontentframe' => 'rcmail_messagecontent_frame',
1767   'messagepartframe' => 'rcmail_message_part_frame',
1768   'messagepartcontrols' => 'rcmail_message_part_controls',
1769   'searchfilter' => 'rcmail_search_filter',
1770   'searchform' => array($OUTPUT, 'search_form'),
1771 ));
1772
1773