]> git.donarmstrong.com Git - roundcube.git/blob - program/steps/mail/func.inc
Imported Upstream version 0.3
[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-2009, 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 2880 2009-08-27 09:52:52Z alec $
19
20 */
21
22 $EMAIL_ADDRESS_PATTERN = '([a-z0-9][a-z0-9\-\.\+\_]*@[a-z0-9][a-z0-9\-\.]*\\.[a-z]{2,5})';
23
24 // actions that do not require imap connection
25 $NOIMAP_ACTIONS = array('spell', 'addcontact', 'autocomplete', 'upload', 'display-attachment', 'remove-attachment');
26
27
28 // log in to imap server
29 if (!in_array($RCMAIL->action, $NOIMAP_ACTIONS) && !$RCMAIL->imap_connect()) {
30   $RCMAIL->kill_session();
31
32   if ($OUTPUT->ajax_call)
33     $OUTPUT->redirect(array(), 2000);
34
35   $OUTPUT->set_env('task', 'login');
36   $OUTPUT->send('login');
37 }
38
39
40 // set imap properties and session vars
41 if ($mbox = get_input_value('_mbox', RCUBE_INPUT_GPC))
42   $IMAP->set_mailbox(($_SESSION['mbox'] = $mbox));
43 else
44   $_SESSION['mbox'] = $IMAP->get_mailbox_name();
45
46 if (!empty($_GET['_page']))
47   $IMAP->set_page(($_SESSION['page'] = intval($_GET['_page'])));
48
49 // set default sort col/order to session
50 if (!isset($_SESSION['sort_col']))
51   $_SESSION['sort_col'] = $CONFIG['message_sort_col'];
52 if (!isset($_SESSION['sort_order']))
53   $_SESSION['sort_order'] = $CONFIG['message_sort_order'];
54
55 // set message set for search result
56 if (!empty($_REQUEST['_search']) && isset($_SESSION['search'][$_REQUEST['_search']]))
57   {
58   $IMAP->set_search_set($_SESSION['search'][$_REQUEST['_search']]);
59   $OUTPUT->set_env('search_request', $_REQUEST['_search']);
60   $OUTPUT->set_env('search_text', $_SESSION['last_text_search']);
61   }
62
63 // set main env variables, labels and page title
64 if (empty($RCMAIL->action) || $RCMAIL->action == 'list')
65   {
66   $mbox_name = $IMAP->get_mailbox_name();
67
68   if (empty($RCMAIL->action))
69     {
70     // initialize searching result if search_filter is used
71     if ($_SESSION['search_filter'] && $_SESSION['search_filter'] != 'ALL')
72       {
73       $search_request = md5($mbox_name.$_SESSION['search_filter']);
74   
75       $IMAP->search($mbox_name, $_SESSION['search_filter'], RCMAIL_CHARSET, $_SESSION['sort_col']);
76       $_SESSION['search'][$search_request] = $IMAP->get_search_set();
77       $OUTPUT->set_env('search_request', $search_request);
78       }
79     
80       $OUTPUT->set_env('search_mods', $_SESSION['search_mods'] ? $_SESSION['search_mods'] : array('subject'=>'subject'));
81       // make sure the message count is refreshed (for default view)
82       $IMAP->messagecount($mbox_name, 'ALL', true);
83     }
84         
85   // set current mailbox in client environment
86   $OUTPUT->set_env('mailbox', $mbox_name);
87   $OUTPUT->set_env('quota', $IMAP->get_capability('quota'));
88   $OUTPUT->set_env('delimiter', $IMAP->get_hierarchy_delimiter());
89
90   if ($CONFIG['flag_for_deletion'])
91     $OUTPUT->set_env('flag_for_deletion', true);
92   if ($CONFIG['read_when_deleted'])
93     $OUTPUT->set_env('read_when_deleted', true);
94   if ($CONFIG['skip_deleted'])
95     $OUTPUT->set_env('skip_deleted', true);
96   if ($CONFIG['display_next'])
97     $OUTPUT->set_env('display_next', true);
98           
99   if ($CONFIG['trash_mbox'])
100     $OUTPUT->set_env('trash_mailbox', $CONFIG['trash_mbox']);
101   if ($CONFIG['drafts_mbox'])
102     $OUTPUT->set_env('drafts_mailbox', $CONFIG['drafts_mbox']);
103   if ($CONFIG['junk_mbox'])
104     $OUTPUT->set_env('junk_mailbox', $CONFIG['junk_mbox']);
105
106   if (!$OUTPUT->ajax_call)
107     $OUTPUT->add_label('checkingmail', 'deletemessage', 'movemessagetotrash', 'movingmessage');
108
109   $OUTPUT->set_pagetitle(rcmail_localize_foldername($mbox_name));
110   }
111
112
113 /**
114  * return the message list as HTML table
115  */
116 function rcmail_message_list($attrib)
117   {
118   global $IMAP, $CONFIG, $COMM_PATH, $OUTPUT;
119
120   $skin_path = $CONFIG['skin_path'];
121   $image_tag = '<img src="%s%s" alt="%s" />';
122
123   // check to see if we have some settings for sorting
124   $sort_col   = $_SESSION['sort_col'];
125   $sort_order = $_SESSION['sort_order'];
126   
127   // add some labels to client
128   $OUTPUT->add_label('from', 'to');
129
130   // get message headers
131   $a_headers = $IMAP->list_headers('', '', $sort_col, $sort_order);
132
133   // add id to message list table if not specified
134   if (!strlen($attrib['id']))
135     $attrib['id'] = 'rcubemessagelist';
136
137   // allow the following attributes to be added to the <table> tag
138   $attrib_str = create_attrib_string($attrib, array('style', 'class', 'id', 'cellpadding', 'cellspacing', 'border', 'summary'));
139
140   $out = '<table' . $attrib_str . ">\n";
141
142   // define list of cols to be displayed based on parameter or config
143   if (empty($attrib['columns']))
144       $a_show_cols = is_array($CONFIG['list_cols']) ? $CONFIG['list_cols'] : array('subject');
145   else
146       $a_show_cols = preg_split('/[\s,;]+/', strip_quotes($attrib['columns']));
147
148   // store column list in a session-variable
149   $_SESSION['list_columns'] = $a_show_cols;
150   
151   // define sortable columns
152   $a_sort_cols = array('subject', 'date', 'from', 'to', 'size');
153
154   $mbox = $IMAP->get_mailbox_name();
155   
156   // show 'to' instead of from in sent messages
157   if (($mbox==$CONFIG['sent_mbox'] || $mbox==$CONFIG['drafts_mbox']) && ($f = array_search('from', $a_show_cols))
158       && !array_search('to', $a_show_cols))
159     $a_show_cols[$f] = 'to';
160   
161   // add col definition
162   $out .= '<colgroup>';
163   $out .= '<col class="icon" />';
164
165   foreach ($a_show_cols as $col)
166     $out .= ($col!='attachment') ? sprintf('<col class="%s" />', $col) : '<col class="icon" />';
167
168   $out .= "</colgroup>\n";
169
170   // add table title
171   $out .= "<thead><tr>\n<td class=\"icon\">&nbsp;</td>\n";
172
173   $javascript = '';
174   foreach ($a_show_cols as $col)
175     {
176     // get column name
177     switch ($col)
178       {
179       case 'flag':
180         $col_name = sprintf($image_tag, $skin_path, $attrib['unflaggedicon'], '');
181         break;
182       case 'attachment':
183         $col_name = sprintf($image_tag, $skin_path, $attrib['attachmenticon'], '');
184         break;
185       default:
186         $col_name = Q(rcube_label($col));
187     }
188
189     // make sort links
190     $sort = '';
191     if (in_array($col, $a_sort_cols))
192       {
193       // have buttons configured
194       if (!empty($attrib['sortdescbutton']) || !empty($attrib['sortascbutton']))
195         {
196         $sort = '&nbsp;&nbsp;';
197
198         // asc link
199         if (!empty($attrib['sortascbutton']))
200           {
201           $sort .= $OUTPUT->button(array(
202             'command' => 'sort',
203             'prop' => $col.'_ASC',
204             'image' => $attrib['sortascbutton'],
205             'align' => 'absmiddle',
206             'title' => 'sortasc'));
207           }       
208         
209         // desc link
210         if (!empty($attrib['sortdescbutton']))
211           {
212           $sort .= $OUTPUT->button(array(
213             'command' => 'sort',
214             'prop' => $col.'_DESC',
215             'image' => $attrib['sortdescbutton'],
216             'align' => 'absmiddle',
217             'title' => 'sortdesc'));
218           }
219         }
220       // just add a link tag to the header
221       else
222         {
223         $col_name = sprintf(
224           '<a href="./#sort" onclick="return %s.command(\'sort\',\'%s\',this)" title="%s">%s</a>',
225           JS_OBJECT_NAME,
226           $col,
227           rcube_label('sortby'),
228           $col_name);
229         }
230       }
231       
232     $sort_class = $col==$sort_col ? " sorted$sort_order" : '';
233
234     // put it all together
235     if ($col!='attachment')
236       $out .= '<td class="'.$col.$sort_class.'" id="rcm'.$col.'">' . "$col_name$sort</td>\n";
237     else    
238       $out .= '<td class="icon" id="rcm'.$col.'">' . "$col_name$sort</td>\n";
239     }
240
241   $out .= "</tr></thead>\n<tbody>\n";
242
243   // no messages in this mailbox
244   if (!sizeof($a_headers))
245     $OUTPUT->show_message('nomessagesfound', 'notice');
246
247   $a_js_message_arr = array();
248
249   // create row for each message
250   foreach ($a_headers as $i => $header)  //while (list($i, $header) = each($a_headers))
251     {
252     $message_icon = $attach_icon = $flagged_icon = '';
253     $js_row_arr = array();
254     $zebra_class = $i%2 ? ' even' : ' odd';
255
256     // set messag attributes to javascript array
257     if ($header->deleted)
258       $js_row_arr['deleted'] = true;
259     if (!$header->seen)
260       $js_row_arr['unread'] = true;
261     if ($header->answered)
262       $js_row_arr['replied'] = true;
263     if ($header->forwarded)
264       $js_row_arr['forwarded'] = true;
265     if ($header->flagged)
266       $js_row_arr['flagged'] = true;
267
268     // set message icon  
269     if ($attrib['deletedicon'] && $header->deleted)
270       $message_icon = $attrib['deletedicon'];
271     else if ($attrib['repliedicon'] && $header->answered)
272       {
273       if ($attrib['forwardedrepliedicon'] && $header->forwarded)
274         $message_icon = $attrib['forwardedrepliedicon'];
275       else
276         $message_icon = $attrib['repliedicon'];
277       }
278     else if ($attrib['forwardedicon'] && $header->forwarded)
279       $message_icon = $attrib['forwardedicon'];
280     else if ($attrib['unreadicon'] && !$header->seen)
281       $message_icon = $attrib['unreadicon'];
282     else if ($attrib['messageicon'])
283       $message_icon = $attrib['messageicon'];
284
285     if ($attrib['flaggedicon'] && $header->flagged)
286       $flagged_icon = $attrib['flaggedicon'];
287     else if ($attrib['unflaggedicon'] && !$header->flagged)
288       $flagged_icon = $attrib['unflaggedicon'];
289     
290     // set attachment icon
291     if ($attrib['attachmenticon'] && preg_match("/multipart\/m/i", $header->ctype))
292       $attach_icon = $attrib['attachmenticon'];
293         
294     $out .= sprintf('<tr id="rcmrow%d" class="message%s%s%s%s">'."\n",
295                     $header->uid,
296                     $header->seen ? '' : ' unread',
297                     $header->deleted ? ' deleted' : '',
298                     $header->flagged ? ' flagged' : '',
299                     $zebra_class);
300     
301     $out .= sprintf("<td class=\"icon\">%s</td>\n", $message_icon ? sprintf($image_tag, $skin_path, $message_icon, '') : '');
302
303     $IMAP->set_charset(!empty($header->charset) ? $header->charset : $CONFIG['default_charset']);
304   
305     // format each col
306     foreach ($a_show_cols as $col)
307       {
308       if ($col=='from' || $col=='to')
309         $cont = Q(rcmail_address_string($header->$col, 3, false, $attrib['addicon']), 'show');
310       else if ($col=='subject')
311         {
312         $action = $mbox==$CONFIG['drafts_mbox'] ? 'compose' : 'show';
313         $uid_param = $mbox==$CONFIG['drafts_mbox'] ? '_draft_uid' : '_uid';
314         $cont = abbreviate_string(trim($IMAP->decode_header($header->$col)), 160);
315         if (empty($cont)) $cont = rcube_label('nosubject');
316         $cont = $OUTPUT->browser->ie ? Q($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));
317         }
318       else if ($col=='flag')
319         $cont = $flagged_icon ? sprintf($image_tag, $skin_path, $flagged_icon, '') : '';
320       else if ($col=='size')
321         $cont = show_bytes($header->$col);
322       else if ($col=='date')
323         $cont = format_date($header->date);
324       else
325         $cont = Q($header->$col);
326         
327       if ($col!='attachment')
328         $out .= '<td class="'.$col.'">' . $cont . "</td>\n";
329       else
330         $out .= sprintf("<td class=\"icon\">%s</td>\n", $attach_icon ? sprintf($image_tag, $skin_path, $attach_icon, '') : '&nbsp;');
331       }
332
333     $out .= "</tr>\n";
334     
335     if (sizeof($js_row_arr))
336       $a_js_message_arr[$header->uid] = $js_row_arr;
337     }
338   
339   // complete message table
340   $out .= "</tbody></table>\n";
341   
342   $message_count = $IMAP->messagecount();
343   
344   // set client env
345   $OUTPUT->add_gui_object('mailcontframe', 'mailcontframe');
346   $OUTPUT->add_gui_object('messagelist', $attrib['id']);
347   $OUTPUT->set_env('messagecount', $message_count);
348   $OUTPUT->set_env('current_page', $IMAP->list_page);
349   $OUTPUT->set_env('pagecount', ceil($message_count/$IMAP->page_size));
350   $OUTPUT->set_env('sort_col', $sort_col);
351   $OUTPUT->set_env('sort_order', $sort_order);
352   
353   if ($attrib['messageicon'])
354     $OUTPUT->set_env('messageicon', $skin_path . $attrib['messageicon']);
355   if ($attrib['deletedicon'])
356     $OUTPUT->set_env('deletedicon', $skin_path . $attrib['deletedicon']);
357   if ($attrib['unreadicon'])
358     $OUTPUT->set_env('unreadicon', $skin_path . $attrib['unreadicon']);
359   if ($attrib['repliedicon'])
360     $OUTPUT->set_env('repliedicon', $skin_path . $attrib['repliedicon']);
361   if ($attrib['forwardedicon'])
362     $OUTPUT->set_env('forwardedicon', $skin_path . $attrib['forwardedicon']);
363   if ($attrib['forwardedrepliedicon'])
364     $OUTPUT->set_env('forwardedrepliedicon', $skin_path . $attrib['forwardedrepliedicon']);
365   if ($attrib['attachmenticon'])
366     $OUTPUT->set_env('attachmenticon', $skin_path . $attrib['attachmenticon']);
367   if ($attrib['flaggedicon'])
368     $OUTPUT->set_env('flaggedicon', $skin_path . $attrib['flaggedicon']);
369   if ($attrib['unflaggedicon'])
370     $OUTPUT->set_env('unflaggedicon', $skin_path . $attrib['unflaggedicon']);
371   
372   $OUTPUT->set_env('messages', $a_js_message_arr);
373   $OUTPUT->set_env('coltypes', $a_show_cols);
374   
375   $OUTPUT->include_script('list.js');
376   
377   return $out;
378   }
379
380
381 /**
382  * return javascript commands to add rows to the message list
383  * or to replace the whole list (IE only)
384  */
385 function rcmail_js_message_list($a_headers, $insert_top=FALSE, $replace=TRUE)
386   {
387   global $CONFIG, $IMAP, $OUTPUT;
388
389   if (empty($_SESSION['list_columns']))
390     $a_show_cols = is_array($CONFIG['list_cols']) ? $CONFIG['list_cols'] : array('subject');
391   else
392     $a_show_cols = $_SESSION['list_columns'];
393
394   $mbox = $IMAP->get_mailbox_name();
395
396   // show 'to' instead of from in sent messages
397   if (($mbox == $CONFIG['sent_mbox'] || $mbox == $CONFIG['drafts_mbox'])
398       && (($f = array_search('from', $a_show_cols)) !== false) && array_search('to', $a_show_cols) === false)
399     $a_show_cols[$f] = 'to';
400
401   $browser = new rcube_browser;
402
403   $OUTPUT->command('set_message_coltypes', $a_show_cols);
404   if ($browser->ie && $replace)
405     $OUTPUT->command('offline_message_list', true);
406
407   // loop through message headers
408   foreach ($a_headers as $n => $header)
409     {
410     $a_msg_cols = array();
411     $a_msg_flags = array();
412     
413     if (empty($header))
414       continue;
415
416     $IMAP->set_charset(!empty($header->charset) ? $header->charset : $CONFIG['default_charset']);
417
418     // remove 'attachment' and 'flag' columns, we don't need them here
419     if(($key = array_search('attachment', $a_show_cols)) !== FALSE)
420       unset($a_show_cols[$key]);
421     if(($key = array_search('flag', $a_show_cols)) !== FALSE)
422       unset($a_show_cols[$key]);
423
424     // format each col; similar as in rcmail_message_list()
425     foreach ($a_show_cols as $col)
426       {
427       if ($col=='from' || $col=='to')
428         $cont = Q(rcmail_address_string($header->$col, 3), 'show');
429       else if ($col=='subject')
430         {
431         $action = $mbox==$CONFIG['drafts_mbox'] ? 'compose' : 'show';
432         $uid_param = $mbox==$CONFIG['drafts_mbox'] ? '_draft_uid' : '_uid';
433         $cont = abbreviate_string(trim($IMAP->decode_header($header->$col)), 160);
434         if (!$cont) $cont = rcube_label('nosubject');
435         $cont = $browser->ie ? Q($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));
436         }
437       else if ($col=='size')
438         $cont = show_bytes($header->$col);
439       else if ($col=='date')
440         $cont = format_date($header->date);
441       else
442         $cont = Q($header->$col);
443           
444       $a_msg_cols[$col] = $cont;
445       }
446
447     if ($header->deleted)
448       $a_msg_flags['deleted'] = 1;
449     if (!$header->seen)
450       $a_msg_flags['unread'] = 1;
451     if ($header->answered)
452       $a_msg_flags['replied'] = 1;
453     if ($header->forwarded)
454       $a_msg_flags['forwarded'] = 1;
455     if ($header->flagged)
456       $a_msg_flags['flagged'] = 1;
457
458     $OUTPUT->command('add_message_row',
459       $header->uid,
460       $a_msg_cols,
461       $a_msg_flags,
462       preg_match("/multipart\/m/i", $header->ctype),
463       $insert_top);
464     }
465
466     if ($browser->ie && $replace)
467       $OUTPUT->command('offline_message_list', false);
468   }
469
470
471 /**
472  * return an HTML iframe for loading mail content
473  */
474 function rcmail_messagecontent_frame($attrib)
475   {
476   global $OUTPUT;
477   
478   if (empty($attrib['id']))
479     $attrib['id'] = 'rcmailcontentwindow';
480
481   $attrib['name'] = $attrib['id'];
482
483   $OUTPUT->set_env('contentframe', $attrib['id']);
484   $OUTPUT->set_env('blankpage', $attrib['src'] ? $OUTPUT->abs_url($attrib['src']) : 'program/blank.gif');
485
486   return html::iframe($attrib);
487   }
488
489
490 /**
491  *
492  */
493 function rcmail_messagecount_display($attrib)
494   {
495   global $IMAP, $OUTPUT;
496   
497   if (!$attrib['id'])
498     $attrib['id'] = 'rcmcountdisplay';
499
500   $OUTPUT->add_gui_object('countdisplay', $attrib['id']);
501
502   return html::span($attrib, rcmail_get_messagecount_text());
503   }
504
505
506 /**
507  *
508  */
509 function rcmail_quota_display($attrib)
510   {
511   global $OUTPUT, $COMM_PATH;
512
513   if (!$attrib['id'])
514     $attrib['id'] = 'rcmquotadisplay';
515
516   if(isset($attrib['display']))
517     $_SESSION['quota_display'] = $attrib['display'];
518
519   $OUTPUT->add_gui_object('quotadisplay', $attrib['id']);
520
521   return html::span($attrib, rcmail_quota_content(NULL, $attrib));
522   }
523
524
525 /**
526  *
527  */
528 function rcmail_quota_content($quota=NULL, $attrib=NULL)
529   {
530   global $IMAP, $COMM_PATH, $RCMAIL;
531
532   $display = isset($_SESSION['quota_display']) ? $_SESSION['quota_display'] : '';
533
534   if (is_array($quota) && !empty($quota['used']) && !empty($quota['total']))
535     {
536       if (!isset($quota['percent']))
537         $quota['percent'] = $quota['used'] / $quota['total'];
538     }
539   elseif (!$IMAP->get_capability('QUOTA'))
540     return rcube_label('unknown');
541   else
542     $quota = $IMAP->get_quota();
543
544   if ($quota && !($quota['total']==0 && $RCMAIL->config->get('quota_zero_as_unlimited')))
545     {
546     $quota_text = sprintf('%s / %s (%.0f%%)',
547                           show_bytes($quota['used'] * 1024),
548                           show_bytes($quota['total'] * 1024),
549                           $quota['percent']);
550
551     // show quota as image (by Brett Patterson)
552     if ($display == 'image' && function_exists('imagegif'))
553       {
554       if (!$attrib['width'])
555         $attrib['width'] = isset($_SESSION['quota_width']) ? $_SESSION['quota_width'] : 100;
556       else
557         $_SESSION['quota_width'] = $attrib['width'];
558
559       if (!$attrib['height'])
560         $attrib['height'] = isset($_SESSION['quota_height']) ? $_SESSION['quota_height'] : 14;
561       else
562         $_SESSION['quota_height'] = $attrib['height'];
563             
564       $quota_text = sprintf('<img src="./bin/quotaimg.php?u=%s&amp;q=%d&amp;w=%d&amp;h=%d" width="%d" height="%d" alt="%s" title="%s / %s" />',
565                             $quota['used'], $quota['total'],
566                             $attrib['width'], $attrib['height'],
567                             $attrib['width'], $attrib['height'],
568                             $quota_text,
569                             show_bytes($quota['used'] * 1024),
570                             show_bytes($quota['total'] * 1024));
571       }
572     }
573   else
574     $quota_text = rcube_label('unlimited');
575
576   return $quota_text;
577   }
578
579
580 /**
581  *
582  */
583 function rcmail_get_messagecount_text($count=NULL, $page=NULL)
584   {
585   global $IMAP, $MESSAGE;
586   
587   if (isset($MESSAGE->index))
588     {
589     return rcube_label(array('name' => 'messagenrof',
590                              'vars' => array('nr'  => $MESSAGE->index+1,
591                                              'count' => $count!==NULL ? $count : $IMAP->messagecount())));
592     }
593
594   if ($page===NULL)
595     $page = $IMAP->list_page;
596     
597   $start_msg = ($page-1) * $IMAP->page_size + 1;
598   $max = $count!==NULL ? $count : $IMAP->messagecount();
599
600   if ($max==0)
601     $out = rcube_label('mailboxempty');
602   else
603     $out = rcube_label(array('name' => 'messagesfromto',
604                               'vars' => array('from'  => $start_msg,
605                                               'to'    => min($max, $start_msg + $IMAP->page_size - 1),
606                                               'count' => $max)));
607
608   return Q($out);
609   }
610
611 /**
612  *
613  */
614 function rcmail_mailbox_name_display($attrib)
615 {
616     global $RCMAIL;
617
618     if (!$attrib['id'])
619         $attrib['id'] = 'rcmmailboxname';
620
621     $RCMAIL->output->add_gui_object('mailboxname', $attrib['id']);
622
623     return html::span($attrib, rcmail_get_mailbox_name_text());
624 }
625
626 function rcmail_get_mailbox_name_text()
627 {
628     global $RCMAIL;
629     return rcmail_localize_foldername($RCMAIL->imap->get_mailbox_name());
630 }
631
632 /**
633  * Sets message is_safe flag according to 'show_images' option value
634  *
635  * @param object rcube_message Message
636  */
637 function rcmail_check_safe(&$message)
638 {
639   global $RCMAIL;
640
641   $show_images = $RCMAIL->config->get('show_images');
642   if (!$message->is_safe
643     && !empty($show_images)
644     && $message->has_html_part())
645   {
646     switch($show_images) {
647       case '1': // known senders only
648         $CONTACTS = new rcube_contacts($RCMAIL->db, $_SESSION['user_id']);
649         if ($CONTACTS->search('email', $message->sender['mailto'], true, false)->count) {
650           $message->set_safe(true);
651         }
652       break;
653       case '2': // always
654         $message->set_safe(true);
655       break;
656     }
657   }
658 }
659
660 /**
661  * Cleans up the given message HTML Body (for displaying)
662  *
663  * @param string HTML
664  * @param array  Display parameters 
665  * @param array  CID map replaces (inline images)
666  * @return string Clean HTML
667  */
668 function rcmail_wash_html($html, $p = array(), $cid_replaces)
669 {
670   global $REMOTE_OBJECTS;
671   
672   $p += array('safe' => false, 'inline_html' => true);
673
674   // special replacements (not properly handled by washtml class)
675   $html_search = array(
676     '/(<\/nobr>)(\s+)(<nobr>)/i',       // space(s) between <NOBR>
677     '/<title>.*<\/title>/i',            // PHP bug #32547 workaround: remove title tag
678     '/^(\0\0\xFE\xFF|\xFF\xFE\0\0|\xFE\xFF|\xFF\xFE|\xEF\xBB\xBF)/',    // byte-order mark (only outlook?)
679     '/<html\s[^>]+>/i',                 // washtml/DOMDocument cannot handle xml namespaces
680   );
681   $html_replace = array(
682     '\\1'.' &nbsp; '.'\\3',
683     '',
684     '',
685     '<html>',
686   );
687   $html = preg_replace($html_search, $html_replace, $html);
688
689   // fix (unknown/malformed) HTML tags before "wash"
690   $html = preg_replace_callback('/(<[\/!]*)([^ >]+)/', 'rcmail_html_tag_callback', $html);
691
692   // charset was converted to UTF-8 in rcube_imap::get_message_part(),
693   // -> change charset specification in HTML accordingly
694   $charset_pattern = '(<meta\s+[^>]*)(content=[\'"]?\w+\/\w+;\s*charset)=([a-z0-9-_]+)';
695   if (preg_match("/$charset_pattern/Ui", $html)) {
696     $html = preg_replace("/$charset_pattern/i", '\\1\\2='.RCMAIL_CHARSET, $html);
697   }
698   else {
699     // add meta content-type to malformed messages, washtml cannot work without that
700     if (!preg_match('/<head[^>]*>(.*)<\/head>/Uims', $html))
701       $html = '<head></head>'. $html;
702     $html = substr_replace($html, '<meta http-equiv="Content-Type" content="text/html; charset='.RCMAIL_CHARSET.'" />', intval(stripos($html, '<head>')+6), 0);
703   }
704
705   // turn relative into absolute urls
706   $html = rcmail_resolve_base($html);
707
708   // clean HTML with washhtml by Frederic Motte
709   $wash_opts = array(
710     'show_washed' => false,
711     'allow_remote' => $p['safe'],
712     'blocked_src' => "./program/blocked.gif",
713     'charset' => RCMAIL_CHARSET,
714     'cid_map' => $cid_replaces,
715     'html_elements' => array('body'),
716   );
717     
718   if (!$p['inline_html']) {
719     $wash_opts['html_elements'] = array('html','head','title','body');
720   }
721   if ($p['safe']) {
722     $wash_opts['html_elements'][] = 'link';
723     $wash_opts['html_attribs'] = array('rel','type');
724   }
725     
726   $washer = new washtml($wash_opts);
727   $washer->add_callback('form', 'rcmail_washtml_callback');
728
729   // allow CSS styles, will be sanitized by rcmail_washtml_callback()
730   $washer->add_callback('style', 'rcmail_washtml_callback');
731     
732   $html = $washer->wash($html);
733   $REMOTE_OBJECTS = $washer->extlinks;
734   
735   return $html;
736 }
737
738
739 /**
740  * Convert the given message part to proper HTML
741  * which can be displayed the message view
742  *
743  * @param object rcube_message_part Message part
744  * @param array  Display parameters array 
745  * @return string Formatted HTML string
746  */
747 function rcmail_print_body($part, $p = array())
748 {
749   global $RCMAIL;
750   
751   // trigger plugin hook
752   $data = $RCMAIL->plugins->exec_hook('message_part_before',
753     array('type' => $part->ctype_secondary, 'body' => $part->body) + $p + array('safe' => false, 'plain' => false, 'inline_html' => true));
754
755   // convert html to text/plain
756   if ($data['type'] == 'html' && $data['plain']) {
757     $txt = new html2text($data['body'], false, true);
758     $body = $txt->get_text();
759     $part->ctype_secondary = 'plain';
760   }
761   // text/html
762   else if ($data['type'] == 'html') {
763     $body = rcmail_wash_html($data['body'], $data, $part->replaces);
764     $part->ctype_secondary = $data['type'];
765   }
766   // text/enriched
767   else if ($data['type'] == 'enriched') {
768     $part->ctype_secondary = 'html';
769     require_once('lib/enriched.inc');
770     $body = Q(enriched_to_html($data['body']), 'show');
771   }
772   else {
773     // assert plaintext
774     $body = $part->body;
775     $part->ctype_secondary = $data['type'] = 'plain';
776   }
777   
778   // free some memory (hopefully)
779   unset($data['body']);
780
781   // plaintext postprocessing
782   if ($part->ctype_secondary == 'plain') {
783     // make links and email-addresses clickable
784     $replacements = new rcube_string_replacer;
785     
786     // search for patterns like links and e-mail addresses
787     $body = preg_replace_callback($replacements->link_pattern, array($replacements, 'link_callback'), $body);
788     $body = preg_replace_callback($replacements->mailto_pattern, array($replacements, 'mailto_callback'), $body);
789
790     // split body into single lines
791     $a_lines = preg_split('/\r?\n/', $body);
792     $q_lines = array();
793     $quote_level = 0;
794
795     // find/mark quoted lines...
796     for ($n=0, $cnt=count($a_lines); $n < $cnt; $n++) {
797       $q = 0;
798     
799       if ($a_lines[$n][0] == '>' && preg_match('/^(>+\s*)+/', $a_lines[$n], $regs)) {
800         $q = strlen(preg_replace('/\s/', '', $regs[0]));
801         $a_lines[$n] = substr($a_lines[$n], strlen($regs[0]));
802
803         if ($q > $quote_level)
804           $q_lines[$n]['quote'] = $q - $quote_level;
805         else if ($q < $quote_level)
806           $q_lines[$n]['endquote'] = $quote_level - $q;
807       }
808       else if ($quote_level > 0)
809         $q_lines[$n]['endquote'] = $quote_level;
810
811       $quote_level = $q;
812     }
813
814     // quote plain text
815     $body = Q(join("\n", $a_lines), 'replace', false);
816
817     // colorize signature
818     if (($sp = strrpos($body, '-- ')) !== false)
819       if (($sp == 0 || $body[$sp-1] == "\n") && $body[$sp+3] == "\n") {
820         $body = substr($body, 0, max(0, $sp))
821             .'<span class="sig">'.substr($body, $sp).'</span>';
822       }
823
824     // colorize quoted lines
825     $a_lines = preg_split('/\n/', $body);
826     foreach ($q_lines as $i => $q)
827       if ($q['quote'])
828         $a_lines[$i] = str_repeat('<blockquote>', $q['quote']) . $a_lines[$i];
829       else if ($q['endquote'])
830         $a_lines[$i] = str_repeat('</blockquote>', $q['endquote']) . $a_lines[$i];
831
832     // insert the links for urls and mailtos
833     $body = $replacements->resolve(join("\n", $a_lines));
834   }
835
836   // allow post-processing of the message body
837   $data = $RCMAIL->plugins->exec_hook('message_part_after', array('type' => $part->ctype_secondary, 'body' => $body) + $data);
838
839   return $data['type'] == 'html' ? $data['body'] : html::tag('pre', array(), $data['body']);
840 }
841
842
843 /**
844  * add a string to the replacement array and return a replacement string
845  */
846 function rcmail_str_replacement($str, &$rep)
847 {
848   static $count = 0;
849   $rep[$count] = stripslashes($str);
850   return "##string_replacement{".($count++)."}##";
851 }
852
853
854 /**
855  * Callback function for washtml cleaning class
856  */
857 function rcmail_washtml_callback($tagname, $attrib, $content)
858 {
859   switch ($tagname) {
860     case 'form':
861       $out = html::div('form', $content);
862       break;
863       
864     case 'style':
865       // decode all escaped entities and reduce to ascii strings
866       $stripped = preg_replace('/[^a-zA-Z\(:]/', '', rcmail_xss_entity_decode($content));
867       
868       // now check for evil strings like expression, behavior or url()
869       if (!preg_match('/expression|behavior|url\(|import/', $stripped)) {
870         $out = html::tag('style', array('type' => 'text/css'), $content);
871         break;
872       }
873     
874     default:
875       $out = '';
876   }
877   
878   return $out;
879 }
880
881
882 /**
883  * Callback function for HTML tags fixing
884  */
885 function rcmail_html_tag_callback($matches)
886 {
887   $tagname = $matches[2];
888
889   $tagname = preg_replace(array(
890     '/:.*$/',           // Microsoft's Smart Tags <st1:xxxx>
891     '/[^a-z0-9_-]/i',   // forbidden characters
892     ), '', $tagname);
893
894   return $matches[1].$tagname;
895 }
896
897
898 /**
899  * return table with message headers
900  */
901 function rcmail_message_headers($attrib, $headers=NULL)
902   {
903   global $IMAP, $OUTPUT, $MESSAGE, $PRINT_MODE, $RCMAIL;
904   static $sa_attrib;
905   
906   // keep header table attrib
907   if (is_array($attrib) && !$sa_attrib)
908     $sa_attrib = $attrib;
909   else if (!is_array($attrib) && is_array($sa_attrib))
910     $attrib = $sa_attrib;
911   
912   if (!isset($MESSAGE))
913     return FALSE;
914
915   // get associative array of headers object
916   if (!$headers)
917     $headers = is_object($MESSAGE->headers) ? get_object_vars($MESSAGE->headers) : $MESSAGE->headers;
918
919   // show these headers
920   $standard_headers = array('subject', 'from', 'to', 'cc', 'bcc', 'replyto', 'date');
921   $output_headers = array();
922
923   foreach ($standard_headers as $hkey) {
924     if (!$headers[$hkey])
925       continue;
926
927     if ($hkey == 'date') {
928       if ($PRINT_MODE)
929         $header_value = format_date($headers[$hkey], $RCMAIL->config->get('date_long', 'x'));
930       else
931         $header_value = format_date($headers[$hkey]);
932     }
933     else if ($hkey == 'replyto') {
934       if ($headers['replyto'] != $headers['from'])
935         $header_value = rcmail_address_string($headers['replyto'], null, true, $attrib['addicon']);
936       else
937         continue;
938     }
939     else if (in_array($hkey, array('from', 'to', 'cc', 'bcc')))
940       $header_value = rcmail_address_string($headers[$hkey], null, true, $attrib['addicon']);
941     else if ($hkey == 'subject' && empty($headers[$hkey]))
942       $header_value = rcube_label('nosubject');
943     else
944       $header_value = trim($IMAP->decode_header($headers[$hkey]));
945       
946     $output_headers[$hkey] = array('title' => rcube_label($hkey), 'value' => $header_value, 'raw' => $headers[$hkey]);
947   }
948     
949   $plugin = $RCMAIL->plugins->exec_hook('message_headers_output', array('output' => $output_headers, 'headers' => $MESSAGE->headers));
950   
951   // compose html table
952   $table = new html_table(array('cols' => 2));
953   
954   foreach ($plugin['output'] as $hkey => $row) {
955     $table->add(array('class' => 'header-title'), Q($row['title']));
956     $table->add(array('class' => $hkey, 'width' => "90%"), Q($row['value'], ($hkey == 'subject' ? 'strict' : 'show')));
957   }
958
959   // all headers division
960   $table->add(array('colspan' => 2, 'class' => "more-headers show-headers", 'onclick' => "return ".JS_OBJECT_NAME.".command('load-headers','',this)"), '');
961   $table->add_row(array('id' => "all-headers"));
962   $table->add(array('colspan' => 2, 'class' => "all"), html::div(array('id' => 'headers-source'), ''));
963   
964   $OUTPUT->add_gui_object('all_headers_row', 'all-headers');
965   $OUTPUT->add_gui_object('all_headers_box', 'headers-source');
966
967   return $table->show($attrib);
968   }
969
970
971 /**
972  * Handler for the 'messagebody' GUI object
973  *
974  * @param array Named parameters
975  * @return string HTML content showing the message body
976  */
977 function rcmail_message_body($attrib)
978   {
979   global $CONFIG, $OUTPUT, $MESSAGE, $IMAP, $REMOTE_OBJECTS;
980
981   if (!is_array($MESSAGE->parts) && empty($MESSAGE->body))
982     return '';
983     
984   if (!$attrib['id'])
985     $attrib['id'] = 'rcmailMsgBody';
986
987   $safe_mode = $MESSAGE->is_safe || intval($_GET['_safe']);
988   $out = '';
989   
990   $header_attrib = array();
991   foreach ($attrib as $attr => $value)
992     if (preg_match('/^headertable([a-z]+)$/i', $attr, $regs))
993       $header_attrib[$regs[1]] = $value;
994
995   if (!empty($MESSAGE->parts))
996     {
997     foreach ($MESSAGE->parts as $i => $part)
998       {
999       if ($part->type == 'headers')
1000         $out .= rcmail_message_headers(sizeof($header_attrib) ? $header_attrib : NULL, $part->headers);
1001       else if ($part->type == 'content' && $part->size)
1002         {
1003         if (empty($part->ctype_parameters) || empty($part->ctype_parameters['charset']))
1004           $part->ctype_parameters['charset'] = $MESSAGE->headers->charset;
1005
1006         // fetch part if not available
1007         if (!isset($part->body))
1008           $part->body = $MESSAGE->get_part_content($part->mime_id);
1009
1010         $body = rcmail_print_body($part, array('safe' => $safe_mode, 'plain' => !$CONFIG['prefer_html']));
1011
1012         if ($part->ctype_secondary == 'html')
1013           $out .= html::div('message-htmlpart', rcmail_html4inline($body, $attrib['id']));
1014         else
1015           $out .= html::div('message-part', $body);
1016         }
1017       }
1018     }
1019   else
1020     $out .= html::div('message-part', html::tag('pre', array(), Q($MESSAGE->body)));
1021
1022   $ctype_primary = strtolower($MESSAGE->structure->ctype_primary);
1023   $ctype_secondary = strtolower($MESSAGE->structure->ctype_secondary);
1024
1025   // list images after mail body
1026   if ($CONFIG['inline_images']
1027       && $ctype_primary == 'multipart'
1028       && !empty($MESSAGE->attachments) 
1029       && !strstr($message_body, '<html'))
1030     {
1031     foreach ($MESSAGE->attachments as $attach_prop) {
1032       if (strpos($attach_prop->mimetype, 'image/') === 0) {
1033         $out .= html::tag('hr') . html::p(array('align' => "center"),
1034           html::img(array(
1035             'src' => $MESSAGE->get_part_url($attach_prop->mime_id),
1036             'title' => $attach_prop->filename,
1037             'alt' => $attach_prop->filename,
1038           )));
1039         }
1040     }
1041   }
1042   
1043   // tell client that there are blocked remote objects
1044   if ($REMOTE_OBJECTS && !$safe_mode)
1045     $OUTPUT->set_env('blockedobjects', true);
1046
1047   return html::div($attrib, $out);
1048   }
1049
1050
1051 /**
1052  * Convert all relative URLs according to a <base> in HTML
1053  */
1054 function rcmail_resolve_base($body)
1055 {
1056   // check for <base href=...>
1057   if (preg_match('!(<base.*href=["\']?)([hftps]{3,5}://[a-z0-9/.%-]+)!i', $body, $regs)) {
1058     $replacer = new rcube_base_replacer($regs[2]);
1059
1060     // replace all relative paths
1061     $body = preg_replace_callback('/(src|background|href)=(["\']?)([\.\/]+[^"\'\s]+)(\2|\s|>)/Ui', array($replacer, 'callback'), $body);
1062     $body = preg_replace_callback('/(url\s*\()(["\']?)([\.\/]+[^"\'\)\s]+)(\2)\)/Ui', array($replacer, 'callback'), $body);
1063   }
1064
1065   return $body;
1066 }
1067
1068 /**
1069  * modify a HTML message that it can be displayed inside a HTML page
1070  */
1071 function rcmail_html4inline($body, $container_id)
1072   {
1073   $last_style_pos = 0;
1074   $body_lc = strtolower($body);
1075   
1076   // find STYLE tags
1077   while (($pos = strpos($body_lc, '<style', $last_style_pos)) && ($pos2 = strpos($body_lc, '</style>', $pos)))
1078     {
1079     $pos = strpos($body_lc, '>', $pos)+1;
1080
1081     // replace all css definitions with #container [def]
1082     $styles = rcmail_mod_css_styles(substr($body, $pos, $pos2-$pos), $container_id);
1083
1084     $body = substr($body, 0, $pos) . $styles . substr($body, $pos2);
1085     $body_lc = strtolower($body);
1086     $last_style_pos = $pos2;
1087     }
1088
1089   // modify HTML links to open a new window if clicked
1090   $GLOBALS['rcmail_html_container_id'] = $container_id;
1091   $body = preg_replace_callback('/<(a|link)\s+([^>]+)>/Ui', 'rcmail_alter_html_link', $body);
1092   unset($GLOBALS['rcmail_html_container_id']);
1093
1094   // add comments arround html and other tags
1095   $out = preg_replace(array(
1096       '/(<!DOCTYPE[^>]*>)/i',
1097       '/(<\?xml[^>]*>)/i',
1098       '/(<\/?html[^>]*>)/i',
1099       '/(<\/?head[^>]*>)/i',
1100       '/(<title[^>]*>.*<\/title>)/Ui',
1101       '/(<\/?meta[^>]*>)/i'),
1102     '<!--\\1-->',
1103     $body);
1104
1105   $out = preg_replace(
1106     array('/<body([^>]*)>/i', '/<\/body>/i'),
1107     array('<div class="rcmBody"\\1>', '</div>'),
1108     $out);
1109
1110   // quote <? of php and xml files that are specified as text/html
1111   $out = preg_replace(array('/<\?/', '/\?>/'), array('&lt;?', '?&gt;'), $out);
1112
1113   return $out;
1114   }
1115
1116
1117 /**
1118  * parse link attributes and set correct target
1119  */
1120 function rcmail_alter_html_link($matches)
1121 {
1122   global $EMAIL_ADDRESS_PATTERN;
1123   
1124   $tag = $matches[1];
1125   $attrib = parse_attrib_string($matches[2]);
1126   $end = '>';
1127
1128   if ($tag == 'link' && preg_match('/^https?:\/\//i', $attrib['href'])) {
1129     $attrib['href'] = "./bin/modcss.php?u=" . urlencode($attrib['href']) . "&amp;c=" . urlencode($GLOBALS['rcmail_html_container_id']);
1130     $end = ' />';
1131   }
1132   else if (preg_match("/^mailto:$EMAIL_ADDRESS_PATTERN/i", $attrib['href'], $mailto)) {
1133     $attrib['href'] = $mailto[0];
1134     $attrib['onclick'] = sprintf(
1135       "return %s.command('compose','%s',this)",
1136       JS_OBJECT_NAME,
1137       JQ($mailto[1]));
1138   }
1139   else if (!empty($attrib['href']) && $attrib['href'][0] != '#') {
1140     $attrib['target'] = '_blank';
1141   }
1142
1143   return "<$tag" . html::attrib_string($attrib, array('href','name','target','onclick','id','class','style','title','rel','type','media')) . $end;
1144 }
1145
1146
1147 /**
1148  * decode address string and re-format it as HTML links
1149  */
1150 function rcmail_address_string($input, $max=null, $linked=false, $addicon=null)
1151 {
1152   global $IMAP, $PRINT_MODE, $CONFIG, $OUTPUT, $EMAIL_ADDRESS_PATTERN;
1153
1154   $a_parts = $IMAP->decode_address_list($input);
1155
1156   if (!sizeof($a_parts))
1157     return $input;
1158
1159   $c = count($a_parts);
1160   $j = 0;
1161   $out = '';
1162
1163   foreach ($a_parts as $part) {
1164     $j++;
1165     if ($PRINT_MODE) {
1166       $out .= sprintf('%s &lt;%s&gt;', Q($part['name']), $part['mailto']);
1167     }
1168     else if (preg_match("/$EMAIL_ADDRESS_PATTERN/i", $part['mailto'])) {
1169       if ($linked) {
1170         $out .= html::a(array(
1171             'href' => 'mailto:'.$part['mailto'],
1172             'onclick' => sprintf("return %s.command('compose','%s',this)", JS_OBJECT_NAME, JQ($part['mailto'])),
1173             'title' => $part['mailto'],
1174             'class' => "rcmContactAddress",
1175           ),
1176         Q($part['name']));
1177       }
1178       else {
1179         $out .= html::span(array('title' => $part['mailto'], 'class' => "rcmContactAddress"), Q($part['name']));
1180       }
1181
1182       if ($addicon) {
1183         $out .= '&nbsp;' . html::a(array(
1184             'href' => "#add",
1185             'onclick' => sprintf("return %s.command('add-contact','%s',this)", JS_OBJECT_NAME, urlencode($part['string'])),
1186             'title' => rcube_label('addtoaddressbook'),
1187           ),
1188           html::img(array(
1189             'src' => $CONFIG['skin_path'] . $addicon,
1190             'alt' => "Add contact",
1191           )));
1192       }
1193     }
1194     else {
1195       if ($part['name'])
1196         $out .= Q($part['name']);
1197       if ($part['mailto'])
1198         $out .= (strlen($out) ? ' ' : '') . sprintf('&lt;%s&gt;', Q($part['mailto']));
1199     }
1200       
1201     if ($c>$j)
1202       $out .= ','.($max ? '&nbsp;' : ' ');
1203         
1204     if ($max && $j==$max && $c>$j) {
1205       $out .= '...';
1206       break;
1207     }
1208   }
1209     
1210   return $out;
1211 }
1212
1213
1214 /**
1215  * Wrap text to a given number of characters per line
1216  * but respect the mail quotation of replies messages (>)
1217  *
1218  * @param string Text to wrap
1219  * @param int The line width
1220  * @return string The wrapped text
1221  */
1222 function rcmail_wrap_quoted($text, $max = 76)
1223 {
1224   // Rebuild the message body with a maximum of $max chars, while keeping quoted message.
1225   $lines = preg_split('/\r?\n/', trim($text));
1226   $out = '';
1227
1228   foreach ($lines as $line) {
1229     if (strlen($line) > $max) {
1230       if (preg_match('/^([>\s]+)/', $line, $regs)) {
1231         $length = strlen($regs[0]);
1232         $prefix = substr($line, 0, $length);
1233
1234         // Remove '> ' from the line, then wordwrap() the line
1235         $line = rc_wordwrap(substr($line, $length), $max - $length);
1236
1237         // Rebuild the line with '> ' at the beginning of each 'subline'
1238         $newline = '';
1239         foreach (explode("\n", $line) as $l) {
1240           $newline .= $prefix . $l . "\n";
1241         }
1242
1243         // Remove the righest newline char
1244         $line = rtrim($newline);
1245       }
1246       else {
1247         $line = rc_wordwrap($line, $max);
1248       }
1249     }
1250
1251     // Append the line
1252     $out .= $line . "\n";
1253   }
1254   
1255   return $out;
1256 }
1257
1258
1259 function rcmail_message_part_controls()
1260   {
1261   global $MESSAGE;
1262   
1263   $part = asciiwords(get_input_value('_part', RCUBE_INPUT_GPC));
1264   if (!is_object($MESSAGE) || !is_array($MESSAGE->parts) || !($_GET['_uid'] && $_GET['_part']) || !$MESSAGE->mime_parts[$part])
1265     return '';
1266     
1267   $part = $MESSAGE->mime_parts[$part];
1268   $table = new html_table(array('cols' => 3));
1269   
1270   if (!empty($part->filename)) {
1271     $table->add('title', Q(rcube_label('filename')));
1272     $table->add(null, Q($part->filename));
1273     $table->add(null, '[' . html::a('?'.str_replace('_frame=', '_download=', $_SERVER['QUERY_STRING']), Q(rcube_label('download'))) . ']');
1274   }
1275   
1276   if (!empty($part->size)) {
1277     $table->add('title', Q(rcube_label('filesize')));
1278     $table->add(null, Q(show_bytes($part->size)));
1279   }
1280   
1281   return $table->show($attrib);
1282   }
1283
1284
1285
1286 function rcmail_message_part_frame($attrib)
1287   {
1288   global $MESSAGE;
1289   
1290   $part = $MESSAGE->mime_parts[asciiwords(get_input_value('_part', RCUBE_INPUT_GPC))];
1291   $ctype_primary = strtolower($part->ctype_primary);
1292
1293   $attrib['src'] = './?' . str_replace('_frame=', ($ctype_primary=='text' ? '_show=' : '_preload='), $_SERVER['QUERY_STRING']);
1294
1295   return html::iframe($attrib);
1296   }
1297
1298
1299 /**
1300  * clear message composing settings
1301  */
1302 function rcmail_compose_cleanup()
1303   {
1304   if (!isset($_SESSION['compose']))
1305     return;
1306
1307   rcmail::get_instance()->plugins->exec_hook('cleanup_attachments',array());
1308   
1309   rcube_sess_unset('compose');
1310   }
1311   
1312
1313 /**
1314  * Send the given message compose object using the configured method
1315  */
1316 function rcmail_deliver_message(&$message, $from, $mailto, &$smtp_error)
1317 {
1318   global $CONFIG, $RCMAIL;
1319
1320   $msg_body = $message->get();
1321   $headers = $message->headers();
1322
1323   // send thru SMTP server using custom SMTP library
1324   if ($CONFIG['smtp_server']) {
1325     // generate list of recipients
1326     $a_recipients = array($mailto);
1327   
1328     if (strlen($headers['Cc']))
1329       $a_recipients[] = $headers['Cc'];
1330     if (strlen($headers['Bcc']))
1331       $a_recipients[] = $headers['Bcc'];
1332   
1333     // clean Bcc from header for recipients
1334     $send_headers = $headers;
1335     unset($send_headers['Bcc']);
1336     // here too, it because txtHeaders() below use $message->_headers not only $send_headers
1337     unset($message->_headers['Bcc']);
1338
1339     // send message
1340     if (!is_object($RCMAIL->smtp))
1341       $RCMAIL->smtp_init(true);
1342      
1343     $sent = $RCMAIL->smtp->send_mail($from, $a_recipients, ($foo = $message->txtHeaders($send_headers, true)), $msg_body);
1344     $smtp_response = $RCMAIL->smtp->get_response();
1345     $smtp_error = $RCMAIL->smtp->get_error();
1346
1347     // log error
1348     if (!$sent)
1349       raise_error(array('code' => 800, 'type' => 'smtp', 'line' => __LINE__, 'file' => __FILE__,
1350                         'message' => "SMTP error: ".join("\n", $smtp_response)), TRUE, FALSE);
1351   }
1352   // send mail using PHP's mail() function
1353   else {
1354     // unset some headers because they will be added by the mail() function
1355     $headers_enc = $message->headers($headers);
1356     $headers_php = $message->_headers;
1357     unset($headers_php['To'], $headers_php['Subject']);
1358     
1359     // reset stored headers and overwrite
1360     $message->_headers = array();
1361     $header_str = $message->txtHeaders($headers_php);
1362     
1363     // #1485779
1364     if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
1365       if (preg_match_all('/<([^@]+@[^>]+)>/', $headers_enc['To'], $m)) {
1366         $headers_enc['To'] = implode(', ', $m[1]);
1367         }
1368       }
1369        
1370     if (ini_get('safe_mode'))
1371       $sent = mail($headers_enc['To'], $headers_enc['Subject'], $msg_body, $header_str);
1372     else
1373       $sent = mail($headers_enc['To'], $headers_enc['Subject'], $msg_body, $header_str, "-f$from");
1374   }
1375   
1376   if ($sent) {
1377     $RCMAIL->plugins->exec_hook('message_sent', array('headers' => $headers, 'body' => $msg_body));
1378     
1379     // remove MDN headers after sending
1380     unset($headers['Return-Receipt-To'], $headers['Disposition-Notification-To']);
1381     
1382     if ($CONFIG['smtp_log']) {
1383       write_log('sendmail', sprintf("User %s [%s]; Message for %s; %s",
1384         $RCMAIL->user->get_username(),
1385         $_SERVER['REMOTE_ADDR'],
1386         $mailto,
1387         !empty($smtp_response) ? join('; ', $smtp_response) : ''));
1388     }
1389   }
1390   
1391   $message->_headers = array();
1392   $message->headers($headers);
1393   
1394   return $sent;
1395 }
1396
1397
1398 function rcmail_send_mdn($uid, &$smtp_error)
1399 {
1400   global $RCMAIL, $IMAP;
1401
1402   $message = new rcube_message($uid);
1403   
1404   if ($message->headers->mdn_to && !$message->headers->mdn_sent &&
1405     ($IMAP->check_permflag('MDNSENT') || $IMAP->check_permflag('*')))
1406   {
1407     $identity = $RCMAIL->user->get_identity();
1408     $sender = format_email_recipient($identity['email'], $identity['name']);
1409     $recipient = array_shift($IMAP->decode_address_list($message->headers->mdn_to));
1410     $mailto = $recipient['mailto'];
1411
1412     $compose = new rcube_mail_mime($RCMAIL->config->header_delimiter());
1413     $compose->setParam(array(
1414       'text_encoding' => 'quoted-printable',
1415       'html_encoding' => 'quoted-printable',
1416       'head_encoding' => 'quoted-printable',
1417       'head_charset'  => RCMAIL_CHARSET,
1418       'html_charset'  => RCMAIL_CHARSET,
1419       'text_charset'  => RCMAIL_CHARSET,
1420     ));
1421     
1422     // compose headers array
1423     $headers = array(
1424       'Date' => date('r'),
1425       'From' => $sender,
1426       'To'   => $message->headers->mdn_to,
1427       'Subject' => rcube_label('receiptread') . ': ' . $message->subject,
1428       'Message-ID' => sprintf('<%s@%s>', md5(uniqid('rcmail'.rand(),true)), $RCMAIL->config->mail_domain($_SESSION['imap_host'])),
1429       'X-Sender' => $identity['email'],
1430       'Content-Type' => 'multipart/report; report-type=disposition-notification',
1431     );
1432     
1433     if ($agent = $RCMAIL->config->get('useragent'))
1434       $headers['User-Agent'] = $agent;
1435
1436     $body = rcube_label("yourmessage") . "\r\n\r\n" .
1437       "\t" . rcube_label("to") . ': ' . rcube_imap::decode_mime_string($message->headers->to, $message->headers->charset) . "\r\n" .
1438       "\t" . rcube_label("subject") . ': ' . $message->subject . "\r\n" .
1439       "\t" . rcube_label("sent") . ': ' . format_date($message->headers->date, $RCMAIL->config->get('date_long')) . "\r\n" .
1440       "\r\n" . rcube_label("receiptnote") . "\r\n";
1441     
1442     $ua = $RCMAIL->config->get('useragent', "RoundCube Webmail (Version ".RCMAIL_VERSION.")");
1443     $report = "Reporting-UA: $ua\r\n";
1444     
1445     if ($message->headers->to)
1446         $report .= "Original-Recipient: {$message->headers->to}\r\n";
1447     
1448     $report .= "Final-Recipient: rfc822; {$identity['email']}\r\n" .
1449                "Original-Message-ID: {$message->headers->messageID}\r\n" .
1450                "Disposition: manual-action/MDN-sent-manually; displayed\r\n";
1451     
1452     $compose->headers($headers);
1453     $compose->setTXTBody(rc_wordwrap($body, 75, "\r\n"));
1454     $compose->addAttachment($report, 'message/disposition-notification', 'MDNPart2.txt', false, '7bit', 'inline');
1455
1456     $sent = rcmail_deliver_message($compose, $identity['email'], $mailto, $smtp_error);
1457
1458     if ($sent)
1459     {
1460       $IMAP->set_flag($message->uid, 'MDNSENT');
1461       return true;
1462     }
1463   }
1464   
1465   return false;
1466 }
1467
1468
1469 function rcmail_search_filter($attrib)
1470 {
1471   global $OUTPUT, $CONFIG;
1472
1473   if (!strlen($attrib['id']))
1474     $attrib['id'] = 'rcmlistfilter';
1475
1476   $attrib['onchange'] = JS_OBJECT_NAME.'.filter_mailbox(this.value)';
1477   
1478   /*
1479     RFC3501 (6.4.4): 'ALL', 'RECENT', 
1480     'ANSWERED', 'DELETED', 'FLAGGED', 'SEEN',
1481     'UNANSWERED', 'UNDELETED', 'UNFLAGGED', 'UNSEEN',
1482     'NEW', // = (RECENT UNSEEN)
1483     'OLD' // = NOT RECENT
1484   */
1485
1486   $select_filter = new html_select($attrib);
1487   $select_filter->add(rcube_label('all'), 'ALL');
1488   $select_filter->add(rcube_label('unread'), 'UNSEEN');
1489   $select_filter->add(rcube_label('flagged'), 'FLAGGED');
1490   $select_filter->add(rcube_label('unanswered'), 'UNANSWERED');
1491   if (!$CONFIG['skip_deleted'])
1492     $select_filter->add(rcube_label('deleted'), 'DELETED');
1493
1494   $out = $select_filter->show($_SESSION['search_filter']);
1495
1496   $OUTPUT->add_gui_object('search_filter', $attrib['id']);
1497
1498   return $out;                                                                          
1499 }
1500
1501 // register UI objects
1502 $OUTPUT->add_handlers(array(
1503   'mailboxlist' => 'rcmail_mailbox_list',
1504   'messages' => 'rcmail_message_list',
1505   'messagecountdisplay' => 'rcmail_messagecount_display',
1506   'quotadisplay' => 'rcmail_quota_display',
1507   'mailboxname' => 'rcmail_mailbox_name_display',
1508   'messageheaders' => 'rcmail_message_headers',
1509   'messagebody' => 'rcmail_message_body',
1510   'messagecontentframe' => 'rcmail_messagecontent_frame',
1511   'messagepartframe' => 'rcmail_message_part_frame',
1512   'messagepartcontrols' => 'rcmail_message_part_controls',
1513   'searchfilter' => 'rcmail_search_filter',
1514   'searchform' => array($OUTPUT, 'search_form'),
1515 ));
1516
1517 ?>