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