thomascube
2006-02-22 745b1466fc76d5ded589e2469328086002430c1c
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                     |
8  | Copyright (C) 2005, 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
22 require_once('lib/html2text.inc');
23 require_once('lib/enriched.inc');
24
25
26 $EMAIL_ADDRESS_PATTERN = '/([a-z0-9][a-z0-9\-\.\+\_]*@[a-z0-9]([a-z0-9\-][.]?)*[a-z0-9]\\.[a-z]{2,5})/i';
27
28 // set imap properties and session vars
29 if (strlen($_GET['_mbox']))
30   {
31   $IMAP->set_mailbox($_GET['_mbox']);
32   $_SESSION['mbox'] = $_GET['_mbox'];
33   }
34
35 if (strlen($_GET['_page']))
36   {
37   $IMAP->set_page($_GET['_page']);
38   $_SESSION['page'] = $_GET['_page'];
39   }
40
41
6a35c8 42 // set default sort col/order to session
T 43 if (!isset($_SESSION['sort_col']))
44   $_SESSION['sort_col'] = $CONFIG['message_sort_col'];
45 if (!isset($_SESSION['sort_order']))
46   $_SESSION['sort_order'] = $CONFIG['message_sort_order'];
47   
48
4e17e6 49 // define url for getting message parts
T 50 if (strlen($_GET['_uid']))
51   $GET_URL = sprintf('%s&_action=get&_mbox=%s&_uid=%d', $COMM_PATH, $IMAP->get_mailbox_name(), $_GET['_uid']);
52
53
54 // set current mailbox in client environment
55 $OUTPUT->add_script(sprintf("%s.set_env('mailbox', '%s');", $JS_OBJECT_NAME, $IMAP->get_mailbox_name()));
56
57
58 if ($CONFIG['trash_mbox'])
59   $OUTPUT->add_script(sprintf("%s.set_env('trash_mailbox', '%s');", $JS_OBJECT_NAME, $CONFIG['trash_mbox']));
60
61
62
63 // return the mailboxlist in HTML
64 function rcmail_mailbox_list($attrib)
65   {
66   global $IMAP, $CONFIG, $OUTPUT, $JS_OBJECT_NAME, $COMM_PATH;
67   static $s_added_script = FALSE;
597170 68   static $a_mailboxes;
5e3512 69
T 70   // add some labels to client
71   rcube_add_label('purgefolderconfirm');
4e17e6 72   
15a9d1 73 // $mboxlist_start = rcube_timer();
T 74   
4e17e6 75   $type = $attrib['type'] ? $attrib['type'] : 'ul';
T 76   $add_attrib = $type=='select' ? array('style', 'class', 'id', 'name', 'onchange') :
77                                   array('style', 'class', 'id');
78                                   
79   if ($type=='ul' && !$attrib['id'])
80     $attrib['id'] = 'rcmboxlist';
81
82   // allow the following attributes to be added to the <ul> tag
83   $attrib_str = create_attrib_string($attrib, $add_attrib);
84  
85   $out = '<' . $type . $attrib_str . ">\n";
86   
87   // add no-selection option
88   if ($type=='select' && $attrib['noselection'])
89     $out .= sprintf('<option value="0">%s</option>'."\n",
90                     rcube_label($attrib['noselection']));
91   
92   // get mailbox list
93   $mbox = $IMAP->get_mailbox_name();
94   
95   // for these mailboxes we have localized labels
96   $special_mailboxes = array('inbox', 'sent', 'drafts', 'trash', 'junk');
97
597170 98
T 99   // build the folders tree
100   if (empty($a_mailboxes))
101     {
102     // get mailbox list
103     $a_folders = $IMAP->list_mailboxes();
104     $delimiter = $IMAP->get_hierarchy_delimiter();
105     $a_mailboxes = array();
15a9d1 106
T 107 // rcube_print_time($mboxlist_start, 'list_mailboxes()');
108
597170 109     foreach ($a_folders as $folder)
T 110       rcmail_build_folder_tree($a_mailboxes, $folder, $delimiter);
111     }
112
113 // var_dump($a_mailboxes);
114
115   if ($type=='select')
cd900d 116     $out .= rcmail_render_folder_tree_select($a_mailboxes, $special_mailboxes, $mbox, $attrib['maxlength']);
597170 117    else
cd900d 118     $out .= rcmail_render_folder_tree_html($a_mailboxes, $special_mailboxes, $mbox, $attrib['maxlength']);
15a9d1 119
T 120 // rcube_print_time($mboxlist_start, 'render_folder_tree()');
597170 121
4e17e6 122
T 123   if ($type=='ul')
124     $OUTPUT->add_script(sprintf("%s.gui_object('mailboxlist', '%s');", $JS_OBJECT_NAME, $attrib['id']));
125
126   return $out . "</$type>";
597170 127   }
T 128
129
130
131
132 // create a hierarchical array of the mailbox list
133 function rcmail_build_folder_tree(&$arrFolders, $folder, $delm='/', $path='')
134   {
135   $pos = strpos($folder, $delm);
136   if ($pos !== false)
137     {
138     $subFolders = substr($folder, $pos+1);
139     $currentFolder = substr($folder, 0, $pos);
140     }
141   else
142     {
143     $subFolders = false;
144     $currentFolder = $folder;
145     }
146
147   $path .= $currentFolder;
148
149   if (!isset($arrFolders[$currentFolder]))
150     {
151     $arrFolders[$currentFolder] = array('id' => $path,
3f9edb 152                                         'name' => rcube_charset_convert($currentFolder, 'UTF-7'),
597170 153                                         'folders' => array());
T 154     }
155
156   if (!empty($subFolders))
157     rcmail_build_folder_tree($arrFolders[$currentFolder]['folders'], $subFolders, $delm, $path.$delm);
158   }
159   
160
161 // return html for a structured list <ul> for the mailbox tree
cd900d 162 function rcmail_render_folder_tree_html(&$arrFolders, &$special, &$mbox, $maxlength, $nestLevel=0)
597170 163   {
c03095 164   global $JS_OBJECT_NAME, $IMAP, $CONFIG, $OUTPUT;
597170 165
T 166   $idx = 0;
167   $out = '';
168   foreach ($arrFolders as $key => $folder)
169     {
170     $zebra_class = ($nestLevel*$idx)%2 ? 'even' : 'odd';
749b07 171     $title = '';
597170 172
T 173     $folder_lc = strtolower($folder['id']);
174     if (in_array($folder_lc, $special))
175       $foldername = rcube_label($folder_lc);
176     else
a95e0e 177       {
3f9edb 178       $foldername = $folder['name'];
597170 179
a95e0e 180       // shorten the folder name to a given length
T 181       if ($maxlength && $maxlength>1)
749b07 182         {
T 183         $fname = abbrevate_string($foldername, $maxlength);
184         if ($fname != $foldername)
185           $title = ' title="'.rep_specialchars_output($foldername, 'html', 'all').'"';
186         $foldername = $fname;
187         }
a95e0e 188       }
cd900d 189
a95e0e 190     // add unread message count display
15a9d1 191     if ($unread_count = $IMAP->messagecount($folder['id'], 'RECENT', ($folder['id']==$mbox)))
597170 192       $foldername .= sprintf(' (%d)', $unread_count);
6a35c8 193       
T 194     // make folder name safe for ids and class names
195     $folder_css = $class_name = preg_replace('/[^a-z0-9\-_]/', '', $folder_lc);
597170 196
6a35c8 197     // set special class for Sent, Drafts, Trash and Junk
T 198     if ($folder['id']==$CONFIG['sent_mbox'])
199       $class_name = 'sent';
200     else if ($folder['id']==$CONFIG['drafts_mbox'])
201       $class_name = 'drafts';
202     else if ($folder['id']==$CONFIG['trash_mbox'])
203       $class_name = 'trash';
204     else if ($folder['id']==$CONFIG['junk_mbox'])
205       $class_name = 'junk';
206
749b07 207     $out .= sprintf('<li id="rcmbx%s" class="mailbox %s %s%s%s"><a href="./#%s" onclick="return %s.command(\'list\',\'%s\')" onmouseup="return %s.mbox_mouse_up(\'%s\')"%s>%s</a>',
6a35c8 208                     $folder_css,
T 209                     $class_name,
597170 210                     $zebra_class,
T 211                     $unread_count ? ' unread' : '',
212                     $folder['id']==$mbox ? ' selected' : '',
213                     $folder['id'],
214                     $JS_OBJECT_NAME,
215                     $folder['id'],
216                     $JS_OBJECT_NAME,
217                     $folder['id'],
749b07 218                     $title,
a95e0e 219                     rep_specialchars_output($foldername, 'html', 'all'));
597170 220
T 221     if (!empty($folder['folders']))
6a35c8 222       $out .= "\n<ul>\n" . rcmail_render_folder_tree_html($folder['folders'], $special, $mbox, $maxlength, $nestLevel+1) . "</ul>\n";
597170 223
T 224     $out .= "</li>\n";
225     $idx++;
226     }
227
228   return $out;
229   }
230
231
232 // return html for a flat list <select> for the mailbox tree
cd900d 233 function rcmail_render_folder_tree_select(&$arrFolders, &$special, &$mbox, $maxlength, $nestLevel=0)
597170 234   {
c03095 235   global $IMAP, $OUTPUT;
597170 236
T 237   $idx = 0;
238   $out = '';
239   foreach ($arrFolders as $key=>$folder)
240     {
7902df 241     $folder_lc = strtolower($folder['id']);
T 242     if (in_array($folder_lc, $special))
243       $foldername = rcube_label($folder_lc);
cd900d 244     else
a95e0e 245       {
3f9edb 246       $foldername = $folder['name'];
a95e0e 247       
T 248       // shorten the folder name to a given length
249       if ($maxlength && $maxlength>1)
250         $foldername = abbrevate_string($foldername, $maxlength);
251       }
cd900d 252
597170 253     $out .= sprintf('<option value="%s">%s%s</option>'."\n",
T 254                     $folder['id'],
255                     str_repeat('&nbsp;', $nestLevel*4),
a95e0e 256                     rep_specialchars_output($foldername, 'html', 'all'));
597170 257
T 258     if (!empty($folder['folders']))
cd900d 259       $out .= rcmail_render_folder_tree_select($folder['folders'], $special, $mbox, $maxlength, $nestLevel+1);
597170 260
T 261     $idx++;
262     }
263
264   return $out;
4e17e6 265   }
T 266
267
268 // return the message list as HTML table
269 function rcmail_message_list($attrib)
270   {
271   global $IMAP, $CONFIG, $COMM_PATH, $OUTPUT, $JS_OBJECT_NAME;
b076a4 272
4e17e6 273   $skin_path = $CONFIG['skin_path'];
T 274   $image_tag = '<img src="%s%s" alt="%s" border="0" />';
b076a4 275
f3b659 276   // check to see if we have some settings for sorting
6a35c8 277   $sort_col   = $_SESSION['sort_col'];
T 278   $sort_order = $_SESSION['sort_order'];
f3b659 279
4e17e6 280   // get message headers
f3b659 281   $a_headers = $IMAP->list_headers('', '', $sort_col, $sort_order);
4e17e6 282
T 283   // add id to message list table if not specified
284   if (!strlen($attrib['id']))
285     $attrib['id'] = 'rcubemessagelist';
286
287   // allow the following attributes to be added to the <table> tag
288   $attrib_str = create_attrib_string($attrib, array('style', 'class', 'id', 'cellpadding', 'cellspacing', 'border', 'summary'));
289
290   $out = '<table' . $attrib_str . ">\n";
e0ddd4 291
T 292
4e17e6 293   // define list of cols to be displayed
T 294   $a_show_cols = is_array($CONFIG['list_cols']) ? $CONFIG['list_cols'] : array('subject');
b076a4 295   $a_sort_cols = array('subject', 'date', 'from', 'to');
4e17e6 296   
T 297   // show 'to' instead of from in sent messages
298   if (strtolower($IMAP->get_mailbox_name())=='sent' && ($f = array_search('from', $a_show_cols)))
299     $a_show_cols[$f] = 'to';
300
e0ddd4 301   // add col definition
T 302   $out .= '<colgroup>';
303   $out .= '<col class="icon">';
304
305   foreach ($a_show_cols as $col)
306     $out .= sprintf('<col class="%s">', $col);
307
308   $out .= '<col class="icon">';
309   $out .= "</colgroup>\n";
4e17e6 310
T 311   // add table title
312   $out .= "<thead><tr>\n<td class=\"icon\">&nbsp;</td>\n";
b076a4 313
f3b659 314   $javascript = '';
4e17e6 315   foreach ($a_show_cols as $col)
f3b659 316     {
T 317     // get column name
318     $col_name = rep_specialchars_output(rcube_label($col));
319
320     // make sort links
321     $sort = '';
1cded8 322     if ($IMAP->get_capability('sort') && in_array($col, $a_sort_cols))
f3b659 323       {
1cded8 324       // have buttons configured
T 325       if (!empty($attrib['sortdescbutton']) || !empty($attrib['sortascbutton']))
326         {
327         $sort = '&nbsp;&nbsp;';
b076a4 328
1cded8 329         // asc link
T 330         if (!empty($attrib['sortascbutton']))
331           {
332           $sort .= rcube_button(array('command' => 'sort',
333                                       'prop' => $col.'_ASC',
334                                       'image' => $attrib['sortascbutton'],
335                                       'align' => 'absmiddle',
336                                       'title' => 'sortasc'));
337           }       
b076a4 338         
1cded8 339         // desc link
T 340         if (!empty($attrib['sortdescbutton']))
341           {
342           $sort .= rcube_button(array('command' => 'sort',
343                                       'prop' => $col.'_DESC',
344                                       'image' => $attrib['sortdescbutton'],
345                                       'align' => 'absmiddle',
346                                       'title' => 'sortdesc'));        
347           }
348         }
349       // just add a link tag to the header
350       else
b076a4 351         {
1cded8 352         $col_name = sprintf('<a href="./#sort" onclick="return %s.command(\'sort\',\'%s\',this)" title="%s">%s</a>',
T 353                             $JS_OBJECT_NAME,
354                             $col,
355                             rcube_label('sortby'),
356                             $col_name);
b076a4 357         }
f3b659 358       }
b076a4 359       
T 360     $sort_class = $col==$sort_col ? " sorted$sort_order" : '';
f3b659 361
T 362     // put it all together
b076a4 363     $out .= '<td class="'.$col.$sort_class.'" id="rcmHead'.$col.'">' . "$col_name$sort</td>\n";    
f3b659 364     }
4e17e6 365
T 366   $out .= '<td class="icon">'.($attrib['attachmenticon'] ? sprintf($image_tag, $skin_path, $attrib['attachmenticon'], '') : '')."</td>\n";
367   $out .= "</tr></thead>\n<tbody>\n";
368
369
370   // no messages in this mailbox
371   if (!sizeof($a_headers))
372     {
122329 373     $out .= rep_specialchars_output(
S 374                 sprintf('<tr><td colspan="%d">%s</td></tr>',
4e17e6 375                    sizeof($a_show_cols)+2,
122329 376                    rcube_label('nomessagesfound')));
4e17e6 377     }
T 378
379
380   $a_js_message_arr = array();
381
382   // create row for each message
383   foreach ($a_headers as $i => $header)  //while (list($i, $header) = each($a_headers))
384     {
385     $message_icon = $attach_icon = '';
386     $js_row_arr = array();
387     $zebra_class = $i%2 ? 'even' : 'odd';
388
389     // set messag attributes to javascript array
390     if (!$header->seen)
391       $js_row_arr['unread'] = true;
392     if ($header->answered)
393       $js_row_arr['replied'] = true;
394
395     // set message icon    
396     if ($attrib['unreadicon'] && !$header->seen)
397       $message_icon = $attrib['unreadicon'];
398     else if ($attrib['repliedicon'] && $header->answered)
399       $message_icon = $attrib['repliedicon'];
400     else if ($attrib['messageicon'])
401       $message_icon = $attrib['messageicon'];
402     
403     // set attachment icon
404     if ($attrib['attachmenticon'] && preg_match("/multipart\/m/i", $header->ctype))
405       $attach_icon = $attrib['attachmenticon'];
406         
15a9d1 407     $out .= sprintf('<tr id="rcmrow%d" class="message%s%s %s">'."\n",
T 408                     $header->uid,
409                     $header->seen ? '' : ' unread',
410                     $header->deleted ? ' deleted' : '',
411                     $zebra_class);    
412     
4e17e6 413     $out .= sprintf("<td class=\"icon\">%s</td>\n", $message_icon ? sprintf($image_tag, $skin_path, $message_icon, '') : '');
T 414         
415     // format each col
416     foreach ($a_show_cols as $col)
417       {
418       if ($col=='from' || $col=='to')
419         $cont = rep_specialchars_output(rcmail_address_string($header->$col, 3, $attrib['addicon']));
420       else if ($col=='subject')
7902df 421         $cont = rep_specialchars_output($IMAP->decode_header($header->$col), 'html', 'all');
4e17e6 422       else if ($col=='size')
T 423         $cont = show_bytes($header->$col);
424       else if ($col=='date')
425         $cont = format_date($header->date); //date('m.d.Y G:i:s', strtotime($header->date));
426       else
7902df 427         $cont = rep_specialchars_output($header->$col, 'html', 'all');
4e17e6 428         
T 429       $out .= '<td class="'.$col.'">' . $cont . "</td>\n";
430       }
431
432     $out .= sprintf("<td class=\"icon\">%s</td>\n", $attach_icon ? sprintf($image_tag, $skin_path, $attach_icon, '') : '');
433     $out .= "</tr>\n";
434     
435     if (sizeof($js_row_arr))
436       $a_js_message_arr[$header->uid] = $js_row_arr;
437     }
438   
439   // complete message table
440   $out .= "</tbody></table>\n";
441   
442   
443   $message_count = $IMAP->messagecount();
444   
445   // set client env
9d04c2 446   $javascript .= sprintf("%s.gui_object('mailcontframe', '%s');\n", $JS_OBJECT_NAME, 'mailcontframe');
f3b659 447   $javascript .= sprintf("%s.gui_object('messagelist', '%s');\n", $JS_OBJECT_NAME, $attrib['id']);
4e17e6 448   $javascript .= sprintf("%s.set_env('messagecount', %d);\n", $JS_OBJECT_NAME, $message_count);
T 449   $javascript .= sprintf("%s.set_env('current_page', %d);\n", $JS_OBJECT_NAME, $IMAP->list_page);
450   $javascript .= sprintf("%s.set_env('pagecount', %d);\n", $JS_OBJECT_NAME, ceil($message_count/$IMAP->page_size));
b076a4 451   $javascript .= sprintf("%s.set_env('sort_col', '%s');\n", $JS_OBJECT_NAME, $sort_col);
T 452   $javascript .= sprintf("%s.set_env('sort_order', '%s');\n", $JS_OBJECT_NAME, $sort_order);
4e17e6 453   
T 454   if ($attrib['messageicon'])
455     $javascript .= sprintf("%s.set_env('messageicon', '%s%s');\n", $JS_OBJECT_NAME, $skin_path, $attrib['messageicon']);
456   if ($attrib['unreadicon'])
457     $javascript .= sprintf("%s.set_env('unreadicon', '%s%s');\n", $JS_OBJECT_NAME, $skin_path, $attrib['unreadicon']);
458   if ($attrib['repliedicon'])
459     $javascript .= sprintf("%s.set_env('repliedicon', '%s%s');\n", $JS_OBJECT_NAME, $skin_path, $attrib['repliedicon']);
460   if ($attrib['attachmenticon'])
461     $javascript .= sprintf("%s.set_env('attachmenticon', '%s%s');\n", $JS_OBJECT_NAME, $skin_path, $attrib['attachmenticon']);
462     
463   $javascript .= sprintf("%s.set_env('messages', %s);", $JS_OBJECT_NAME, array2js($a_js_message_arr));
464   
465   $OUTPUT->add_script($javascript);  
466   
467   return $out;
468   }
469
470
471
472
473 // return javascript commands to add rows to the message list
474 function rcmail_js_message_list($a_headers, $insert_top=FALSE)
475   {
476   global $CONFIG, $IMAP;
477
478   $commands = '';
479   $a_show_cols = is_array($CONFIG['list_cols']) ? $CONFIG['list_cols'] : array('subject');
480
481   // show 'to' instead of from in sent messages
482   if (strtolower($IMAP->get_mailbox_name())=='sent' && ($f = array_search('from', $a_show_cols)))
483     $a_show_cols[$f] = 'to';
484
485   // loop through message headers
486   for ($n=0; $a_headers[$n]; $n++)
487     {
488     $header = $a_headers[$n];
489     $a_msg_cols = array();
490     $a_msg_flags = array();
491       
492     // format each col; similar as in rcmail_message_list()
493     foreach ($a_show_cols as $col)
494       {
495       if ($col=='from' || $col=='to')
496         $cont = rep_specialchars_output(rcmail_address_string($header->$col, 3));
497       else if ($col=='subject')
7902df 498         $cont = rep_specialchars_output($IMAP->decode_header($header->$col), 'html', 'all');
4e17e6 499       else if ($col=='size')
T 500         $cont = show_bytes($header->$col);
501       else if ($col=='date')
502         $cont = format_date($header->date); //date('m.d.Y G:i:s', strtotime($header->date));
503       else
7902df 504         $cont = rep_specialchars_output($header->$col, 'html', 'all');
4e17e6 505           
T 506       $a_msg_cols[$col] = $cont;
507       }
508
509     $a_msg_flags['unread'] = $header->seen ? 0 : 1;
510     $a_msg_flags['replied'] = $header->answered ? 1 : 0;
15a9d1 511     
T 512     if ($header->deleted)
513       $a_msg_flags['deleted'] = 1;
4e17e6 514   
15a9d1 515     $commands .= sprintf("this.add_message_row(%s, %s, %s, %b, %b);\n",
4e17e6 516                          $header->uid,
T 517                          array2js($a_msg_cols),
518                          array2js($a_msg_flags),
15a9d1 519                          preg_match("/multipart\/m/i", $header->ctype),
T 520                          $insert_top);
4e17e6 521     }
T 522
523   return $commands;
524   }
525
526
527
528 function rcmail_messagecount_display($attrib)
529   {
530   global $IMAP, $OUTPUT, $JS_OBJECT_NAME;
531   
532   if (!$attrib['id'])
533     $attrib['id'] = 'rcmcountdisplay';
534
535   $OUTPUT->add_script(sprintf("%s.gui_object('countdisplay', '%s');", $JS_OBJECT_NAME, $attrib['id']));
536
537   // allow the following attributes to be added to the <span> tag
538   $attrib_str = create_attrib_string($attrib, array('style', 'class', 'id'));
539
540   
541   $out = '<span' . $attrib_str . '>';
542   $out .= rcmail_get_messagecount_text();
543   $out .= '</span>';
544   return $out;
545   }
546
547
58e360 548 function rcmail_quota_display($attrib)
T 549   {
550   global $IMAP, $OUTPUT, $JS_OBJECT_NAME;
551
552   if (!$attrib['id'])
553     $attrib['id'] = 'rcmquotadisplay';
554
555   $OUTPUT->add_script(sprintf("%s.gui_object('quotadisplay', '%s');", $JS_OBJECT_NAME, $attrib['id']));
556
557   // allow the following attributes to be added to the <span> tag
558   $attrib_str = create_attrib_string($attrib, array('style', 'class', 'id'));
559
560
561   $out = '<span' . $attrib_str . '>';
562   $out .= $IMAP->get_quota();
563   $out .= '</span>';
564   return $out;
565   }
566
4e17e6 567
T 568 function rcmail_get_messagecount_text()
569   {
570   global $IMAP, $MESSAGE;
571   
572   if (isset($MESSAGE['index']))
573     {
574     return rcube_label(array('name' => 'messagenrof',
575                              'vars' => array('nr'  => $MESSAGE['index']+1,
31b2ce 576                                              'count' => $IMAP->messagecount())));
4e17e6 577     }
31b2ce 578
4e17e6 579   $start_msg = ($IMAP->list_page-1) * $IMAP->page_size + 1;
T 580   $max = $IMAP->messagecount();
581
582   if ($max==0)
583     $out = rcube_label('mailboxempty');
584   else
585     $out = rcube_label(array('name' => 'messagesfromto',
586                               'vars' => array('from'  => $start_msg,
587                                               'to'    => min($max, $start_msg + $IMAP->page_size - 1),
588                                               'count' => $max)));
589
cd900d 590   return rep_specialchars_output($out);
4e17e6 591   }
T 592
593
594 function rcmail_print_body($part, $safe=FALSE, $plain=FALSE) // $body, $ctype_primary='text', $ctype_secondary='plain', $encoding='7bit', $safe=FALSE, $plain=FALSE)
595   {
596   global $IMAP, $REMOTE_OBJECTS, $JS_OBJECT_NAME;
597
598   // extract part properties: body, ctype_primary, ctype_secondary, encoding, parameters
599   extract($part);
600   
601   $block = $plain ? '%s' : '%s'; //'<div style="display:block;">%s</div>';
58e360 602   $body = $IMAP->mime_decode($body, $encoding);  
4e17e6 603   $body = $IMAP->charset_decode($body, $parameters);
T 604
605   // text/html
606   if ($ctype_secondary=='html')
607     {
608     if (!$safe)  // remove remote images and scripts
609       {
610       $remote_patterns = array('/(src|background)=(["\']?)([hftps]{3,5}:\/{2}[^"\'\s]+)(\2|\s|>)/Ui',
611                            //  '/(src|background)=(["\']?)([\.\/]+[^"\'\s]+)(\2|\s|>)/Ui',
612                                '/(<base.*href=["\']?)([hftps]{3,5}:\/{2}[^"\'\s]+)([^<]*>)/i',
613                                '/(<link.*href=["\']?)([hftps]{3,5}:\/{2}[^"\'\s]+)([^<]*>)/i',
614                                '/url\s*\(["\']?([hftps]{3,5}:\/{2}[^"\'\s]+)["\']?\)/i',
615                                '/url\s*\(["\']?([\.\/]+[^"\'\s]+)["\']?\)/i',
616                                '/<script.+<\/script>/Umis');
617
7cc38e 618       $remote_replaces = array('',  // '\\1=\\2#\\4',
4e17e6 619                             // '\\1=\\2#\\4',
T 620                                '',
7cc38e 621                                '',  // '\\1#\\3',
4e17e6 622                                'none',
T 623                                'none',
624                                '');
625       
626       // set flag if message containes remote obejcts that where blocked
627       foreach ($remote_patterns as $pattern)
628         {
629         if (preg_match($pattern, $body))
630           {
631           $REMOTE_OBJECTS = TRUE;
632           break;
633           }
634         }
635
636       $body = preg_replace($remote_patterns, $remote_replaces, $body);
637       }
638
639     return sprintf($block, rep_specialchars_output($body, 'html', '', FALSE));
640     }
641
642   // text/enriched
643   if ($ctype_secondary=='enriched')
644     {
645     $body = enriched_to_html($body);
646     return sprintf($block, rep_specialchars_output($body, 'html'));
647     }
648   else
649     {
650     // make links and email-addresses clickable
651     $convert_patterns = $convert_replaces = $replace_strings = array();
652     
09941e 653     $url_chars = 'a-z0-9_\-\+\*\$\/&%=@#:';
4e17e6 654     $url_chars_within = '\?\.~,!';
T 655
656     $convert_patterns[] = "/([\w]+):\/\/([a-z0-9\-\.]+[a-z]{2,4}([$url_chars$url_chars_within]*[$url_chars])?)/ie";
20a1b3 657     $convert_replaces[] = "rcmail_str_replacement('<a href=\"\\1://\\2\" target=\"_blank\">\\1://\\2</a>', \$replace_strings)";
4e17e6 658
T 659     $convert_patterns[] = "/([^\/:]|\s)(www\.)([a-z0-9\-]{2,}[a-z]{2,4}([$url_chars$url_chars_within]*[$url_chars])?)/ie";
20a1b3 660     $convert_replaces[] = "rcmail_str_replacement('\\1<a href=\"http://\\2\\3\" target=\"_blank\">\\2\\3</a>', \$replace_strings)";
4e17e6 661     
T 662     $convert_patterns[] = '/([a-z0-9][a-z0-9\-\.\+\_]*@[a-z0-9]([a-z0-9\-][.]?)*[a-z0-9]\\.[a-z]{2,5})/ie';
20a1b3 663     $convert_replaces[] = "rcmail_str_replacement('<a href=\"mailto:\\1\" onclick=\"return $JS_OBJECT_NAME.command(\'compose\',\'\\1\',this)\">\\1</a>', \$replace_strings)";
4e17e6 664
T 665     $body = wordwrap(trim($body), 80);
666     $body = preg_replace($convert_patterns, $convert_replaces, $body);
667
668     // split body into single lines
669     $a_lines = preg_split('/\r?\n/', $body);
670
671     // colorize quoted parts
672     for($n=0; $n<sizeof($a_lines); $n++)
673       {
674       $line = $a_lines[$n];
675
676       if ($line{2}=='>')
677         $color = 'red';
678       else if ($line{1}=='>')
679         $color = 'green';
680       else if ($line{0}=='>')
681         $color = 'blue';
682       else
683         $color = FALSE;
684
685       $line = rep_specialchars_output($line, 'html', 'replace', FALSE);
686         
687       if ($color)
688         $a_lines[$n] = sprintf('<font color="%s">%s</font>', $color, $line);
689       else
690         $a_lines[$n] = $line;
691       }
692
693     // insert the links for urls and mailtos
694     $body = preg_replace("/##string_replacement\{([0-9]+)\}##/e", "\$replace_strings[\\1]", join("\n", $a_lines));
695     
696     return sprintf($block, "<pre>\n".$body."\n</pre>");
697     }
698   }
699
700
701
702 // add a string to the replacement array and return a replacement string
703 function rcmail_str_replacement($str, &$rep)
704   {
705   static $count = 0;
706   $rep[$count] = stripslashes($str);
707   return "##string_replacement{".($count++)."}##";
708   }
709
710
711 function rcmail_parse_message($structure, $arg=array(), $recursive=FALSE)
712   {
713   global $IMAP;
714   static $sa_inline_objects = array();
715
716   // arguments are: (bool)$prefer_html, (string)$get_url
717   extract($arg);
718
719   $a_attachments = array();
720   $a_return_parts = array();
721   $out = '';
722
723   $message_ctype_primary = strtolower($structure->ctype_primary);
724   $message_ctype_secondary = strtolower($structure->ctype_secondary);
725
726   // show message headers
727   if ($recursive && is_array($structure->headers) && isset($structure->headers['subject']))
728     $a_return_parts[] = array('type' => 'headers',
729                               'headers' => $structure->headers);
730
731   // print body if message doesn't have multiple parts
732   if ($message_ctype_primary=='text')
733     {
734     $a_return_parts[] = array('type' => 'content',
735                               'body' => $structure->body,
736                               'ctype_primary' => $message_ctype_primary,
737                               'ctype_secondary' => $message_ctype_secondary,
a95e0e 738                               'parameters' => $structure->ctype_parameters,
4e17e6 739                               'encoding' => $structure->headers['content-transfer-encoding']);
T 740     }
741
742   // message contains alternative parts
743   else if ($message_ctype_primary=='multipart' && $message_ctype_secondary=='alternative' && is_array($structure->parts))
744     {
745     // get html/plaintext parts
746     $plain_part = $html_part = $print_part = $related_part = NULL;
747     
748     foreach ($structure->parts as $p => $sub_part)
749       {
750       $sub_ctype_primary = strtolower($sub_part->ctype_primary);
751       $sub_ctype_secondary = strtolower($sub_part->ctype_secondary);
752
753       // check if sub part is 
754       if ($sub_ctype_primary=='text' && $sub_ctype_secondary=='plain')
755         $plain_part = $p;
756       else if ($sub_ctype_primary=='text' && $sub_ctype_secondary=='html')
757         $html_part = $p;
758       else if ($sub_ctype_primary=='text' && $sub_ctype_secondary=='enriched')
759         $enriched_part = $p;
760       else if ($sub_ctype_primary=='multipart' && $sub_ctype_secondary=='related')
761         $related_part = $p;
762       }
763
764     // parse related part (alternative part could be in here)
765     if ($related_part!==NULL && $prefer_html)
766       {
767       list($parts, $attachmnts) = rcmail_parse_message($structure->parts[$related_part], $arg, TRUE);
768       $a_return_parts = array_merge($a_return_parts, $parts);
769       $a_attachments = array_merge($a_attachments, $attachmnts);
770       }
771
772     // print html/plain part
773     else if ($html_part!==NULL && $prefer_html)
774       $print_part = $structure->parts[$html_part];
775     else if ($enriched_part!==NULL)
776       $print_part = $structure->parts[$enriched_part];
777     else if ($plain_part!==NULL)
778       $print_part = $structure->parts[$plain_part];
779
780     // show message body
781     if (is_object($print_part))
782       $a_return_parts[] = array('type' => 'content',
783                                 'body' => $print_part->body,
784                                 'ctype_primary' => strtolower($print_part->ctype_primary),
785                                 'ctype_secondary' => strtolower($print_part->ctype_secondary),
786                                 'parameters' => $print_part->ctype_parameters,
787                                 'encoding' => $print_part->headers['content-transfer-encoding']);
788     // show plaintext warning
789     else if ($html_part!==NULL)
790       $a_return_parts[] = array('type' => 'content',
791                                 'body' => rcube_label('htmlmessage'),
792                                 'ctype_primary' => 'text',
793                                 'ctype_secondary' => 'plain');
794                                 
795     // add html part as attachment
796     if ($html_part!==NULL && $structure->parts[$html_part]!==$print_part)
797       {
798       $html_part = $structure->parts[$html_part];
799       $a_attachments[] = array('filename' => rcube_label('htmlmessage'),
800                                'encoding' => $html_part->headers['content-transfer-encoding'],
801                                'mimetype' => 'text/html',
802                                'part_id'  => $html_part->mime_id,
803                                'size'     => strlen($IMAP->mime_decode($html_part->body, $html_part->headers['content-transfer-encoding'])));
804       }
805     }
806
807   // message contains multiple parts
808   else if ($message_ctype_primary=='multipart' && is_array($structure->parts))
809     {
810     foreach ($structure->parts as $mail_part)
811       {
812       $primary_type = strtolower($mail_part->ctype_primary);
813       $secondary_type = strtolower($mail_part->ctype_secondary);
814
815       // multipart/alternative
816       if ($primary_type=='multipart') // && ($secondary_type=='alternative' || $secondary_type=='mixed' || $secondary_type=='related'))
817         {
818         list($parts, $attachmnts) = rcmail_parse_message($mail_part, $arg, TRUE);
819
820         $a_return_parts = array_merge($a_return_parts, $parts);
821         $a_attachments = array_merge($a_attachments, $attachmnts);
822         }
823
824       // part text/[plain|html] OR message/delivery-status
58e360 825       else if (($primary_type=='text' && ($secondary_type=='plain' || $secondary_type=='html') && $mail_part->disposition!='attachment') ||
4e17e6 826                ($primary_type=='message' && $secondary_type=='delivery-status'))
T 827         {
828         $a_return_parts[] = array('type' => 'content',
829                                   'body' => $mail_part->body,
830                                   'ctype_primary' => $primary_type,
831                                   'ctype_secondary' => $secondary_type,
a95e0e 832                                   'parameters' => $mail_part->ctype_parameters,
4e17e6 833                                   'encoding' => $mail_part->headers['content-transfer-encoding']);
T 834         }
835
836       // part message/*
837       else if ($primary_type=='message')
838         {
839         /* don't parse headers here; they're parsed within the recursive call to rcmail_parse_message()
840         if ($mail_part->parts[0]->headers)
841           $a_return_parts[] = array('type' => 'headers',
842                                     'headers' => $mail_part->parts[0]->headers);
843         */
844                                       
845         list($parts, $attachmnts) = rcmail_parse_message($mail_part->parts[0], $arg, TRUE);
846
847         $a_return_parts = array_merge($a_return_parts, $parts);
848         $a_attachments = array_merge($a_attachments, $attachmnts);
849         }
850
851       // part is file/attachment
b595c9 852       else if ($mail_part->disposition=='attachment' || $mail_part->disposition=='inline' || $mail_part->headers['content-id'] ||
T 853                (empty($mail_part->disposition) && ($mail_part->d_parameters['filename'] || $mail_part->d_parameters['name'])))
4e17e6 854         {
T 855         if ($message_ctype_secondary=='related' && $mail_part->headers['content-id'])
4b0f65 856           $sa_inline_objects[] = array('filename' => rcube_imap::decode_mime_string($mail_part->d_parameters['filename']),
4e17e6 857                                        'mimetype' => strtolower("$primary_type/$secondary_type"),
T 858                                        'part_id'  => $mail_part->mime_id,
859                                        'content_id' => preg_replace(array('/^</', '/>$/'), '', $mail_part->headers['content-id']));
860
861         else if ($mail_part->d_parameters['filename'])
4b0f65 862           $a_attachments[] = array('filename' => rcube_imap::decode_mime_string($mail_part->d_parameters['filename']),
4e17e6 863                                    'encoding' => strtolower($mail_part->headers['content-transfer-encoding']),
T 864                                    'mimetype' => strtolower("$primary_type/$secondary_type"),
865                                    'part_id'  => $mail_part->mime_id,
866                                    'size'     => strlen($IMAP->mime_decode($mail_part->body, $mail_part->headers['content-transfer-encoding'])) /*,
867                                    'content'  => $mail_part->body */);
868                                    
869         else if ($mail_part->ctype_parameters['name'])
4b0f65 870           $a_attachments[] = array('filename' => rcube_imap::decode_mime_string($mail_part->ctype_parameters['name']),
4e17e6 871                                    'encoding' => strtolower($mail_part->headers['content-transfer-encoding']),
T 872                                    'mimetype' => strtolower("$primary_type/$secondary_type"),
873                                    'part_id'  => $mail_part->mime_id,
874                                    'size'     => strlen($IMAP->mime_decode($mail_part->body, $mail_part->headers['content-transfer-encoding'])) /*,
875                                    'content'  => $mail_part->body */);
876                                    
877                                    
878         }
879       }
880
881
882     // if this was a related part try to resolve references
883     if ($message_ctype_secondary=='related' && sizeof($sa_inline_objects))
884       {
885       $a_replace_patters = array();
886       $a_replace_strings = array();
887         
888       foreach ($sa_inline_objects as $inline_object)
889         {
890         $a_replace_patters[] = 'cid:'.$inline_object['content_id'];
891         $a_replace_strings[] = sprintf($get_url, $inline_object['part_id']);
892         }
893       
894       foreach ($a_return_parts as $i => $return_part)
895         {
896         if ($return_part['type']!='content')
897           continue;
898
899         // decode body and replace cid:...
900         $a_return_parts[$i]['body'] = str_replace($a_replace_patters, $a_replace_strings, $IMAP->mime_decode($return_part['body'], $return_part['encoding']));
901         $a_return_parts[$i]['encoding'] = '7bit';
902         }
903       }
904     }
905     
906
907   // join all parts together
908   //$out .= join($part_delimiter, $a_return_parts);
909
910   return array($a_return_parts, $a_attachments);
911   }
912
913
914
915
916 // return table with message headers
917 function rcmail_message_headers($attrib, $headers=NULL)
918   {
919   global $IMAP, $OUTPUT, $MESSAGE;
920   static $sa_attrib;
921   
922   // keep header table attrib
923   if (is_array($attrib) && !$sa_attrib)
924     $sa_attrib = $attrib;
925   else if (!is_array($attrib) && is_array($sa_attrib))
926     $attrib = $sa_attrib;
927   
928   
929   if (!isset($MESSAGE))
930     return FALSE;
931
932   // get associative array of headers object
933   if (!$headers)
934     $headers = is_object($MESSAGE['headers']) ? get_object_vars($MESSAGE['headers']) : $MESSAGE['headers'];
935     
936   $header_count = 0;
937   
938   // allow the following attributes to be added to the <table> tag
939   $attrib_str = create_attrib_string($attrib, array('style', 'class', 'id', 'cellpadding', 'cellspacing', 'border', 'summary'));
940   $out = '<table' . $attrib_str . ">\n";
941
942   // show these headers
bde645 943   $standard_headers = array('subject', 'from', 'organization', 'to', 'cc', 'bcc', 'reply-to', 'date');
4e17e6 944   
T 945   foreach ($standard_headers as $hkey)
946     {
947     if (!$headers[$hkey])
948       continue;
949
b076a4 950     if ($hkey=='date' && !empty($headers[$hkey]))
4e17e6 951       $header_value = format_date(strtotime($headers[$hkey]));
bde645 952     else if (in_array($hkey, array('from', 'to', 'cc', 'bcc', 'reply-to')))
4e17e6 953       $header_value = rep_specialchars_output(rcmail_address_string($IMAP->decode_header($headers[$hkey]), NULL, $attrib['addicon']));
T 954     else
955       $header_value = rep_specialchars_output($IMAP->decode_header($headers[$hkey]), '', 'all');
956
957     $out .= "\n<tr>\n";
1038d5 958     $out .= '<td class="header-title">'.rep_specialchars_output(rcube_label($hkey)).":&nbsp;</td>\n";
4e17e6 959     $out .= '<td class="'.$hkey.'" width="90%">'.$header_value."</td>\n</tr>";
T 960     $header_count++;
961     }
962
963   $out .= "\n</table>\n\n";
964
965   return $header_count ? $out : '';  
966   }
967
968
969
970 function rcmail_message_body($attrib)
971   {
972   global $CONFIG, $OUTPUT, $MESSAGE, $GET_URL, $REMOTE_OBJECTS, $JS_OBJECT_NAME;
973   
974   if (!is_array($MESSAGE['parts']) && !$MESSAGE['body'])
975     return '';
976     
977   if (!$attrib['id'])
978     $attrib['id'] = 'rcmailMsgBody';
979
980   $safe_mode = (bool)$_GET['_safe'];
981   $attrib_str = create_attrib_string($attrib, array('style', 'class', 'id'));
982   $out = '<div '. $attrib_str . ">\n";
983   
984   $header_attrib = array();
985   foreach ($attrib as $attr => $value)
986     if (preg_match('/^headertable([a-z]+)$/i', $attr, $regs))
987       $header_attrib[$regs[1]] = $value;
988
989
990   // this is an ecrypted message
991   // -> create a plaintext body with the according message
992   if (!sizeof($MESSAGE['parts']) && $MESSAGE['headers']->ctype=='multipart/encrypted')
993     {
994     $MESSAGE['parts'][0] = array('type' => 'content',
995                                  'ctype_primary' => 'text',
996                                  'ctype_secondary' => 'plain',
997                                  'body' => rcube_label('encryptedmessage'));
998     }
999   
1000   if ($MESSAGE['parts'])
1001     {
1002     foreach ($MESSAGE['parts'] as $i => $part)
1003       {
1004       if ($part['type']=='headers')
1005         $out .= rcmail_message_headers(sizeof($header_attrib) ? $header_attrib : NULL, $part['headers']);
1006       else if ($part['type']=='content')
1007         {
a95e0e 1008         if (empty($part['parameters']) || empty($part['parameters']['charset']))
T 1009           $part['parameters']['charset'] = $MESSAGE['headers']->charset;
1010         
4e17e6 1011         // $body = rcmail_print_body($part['body'], $part['ctype_primary'], $part['ctype_secondary'], $part['encoding'], $safe_mode);
T 1012         $body = rcmail_print_body($part, $safe_mode);
1013         $out .= '<div class="message-part">';
1014         $out .= rcmail_mod_html_body($body, $attrib['id']);
1015         $out .= "</div>\n";
1016         }
1017       }
1018     }
1019   else
1020     $out .= $MESSAGE['body'];
1021
1022
1023   $ctype_primary = strtolower($MESSAGE['structure']->ctype_primary);
1024   $ctype_secondary = strtolower($MESSAGE['structure']->ctype_secondary);
1025   
1026   // list images after mail body
1027   if (get_boolean($attrib['showimages']) && $ctype_primary=='multipart' && $ctype_secondary=='mixed' &&
1028       sizeof($MESSAGE['attachments']) && !strstr($message_body, '<html') && strlen($GET_URL))
1029     {
1030     foreach ($MESSAGE['attachments'] as $attach_prop)
1031       {
1032       if (strpos($attach_prop['mimetype'], 'image/')===0)
1033         $out .= sprintf("\n<hr />\n<p align=\"center\"><img src=\"%s&_part=%s\" alt=\"%s\" title=\"%s\" /></p>\n",
1034                         $GET_URL, $attach_prop['part_id'],
1035                         $attach_prop['filename'],
1036                         $attach_prop['filename']);
1037       }
1038     }
1039   
1040   // tell client that there are blocked remote objects
1041   if ($REMOTE_OBJECTS && !$safe_mode)
1042     $OUTPUT->add_script(sprintf("%s.set_env('blockedobjects', true);", $JS_OBJECT_NAME));
1043
1044   $out .= "\n</div>";
1045   return $out;
1046   }
1047
1048
1049
1050 // modify a HTML message that it can be displayed inside a HTML page
1051 function rcmail_mod_html_body($body, $container_id)
1052   {
749b07 1053   // remove any null-byte characters before parsing
T 1054   $body = preg_replace('/\x00/', '', $body);
1055   
4e17e6 1056   $last_style_pos = 0;
T 1057   $body_lc = strtolower($body);
1058   
1059   // find STYLE tags
1060   while (($pos = strpos($body_lc, '<style', $last_style_pos)) && ($pos2 = strpos($body_lc, '</style>', $pos)))
1061     {
1062     $pos2 += 8;
1063     $body_pre = substr($body, 0, $pos);
1064     $styles = substr($body, $pos, $pos2-$pos);
1065     $body_post = substr($body, $pos2, strlen($body)-$pos2);
1066     
1067     // replace all css definitions with #container [def]
1068     $styles = rcmail_mod_css_styles($styles, $container_id);
1069     
1070     $body = $body_pre . $styles . $body_post;
1071     $last_style_pos = $pos2;
1072     }
1073
1074
1075   // remove SCRIPT tags
6a35c8 1076   foreach (array('script', 'applet', 'object', 'embed', 'iframe') as $tag)
4e17e6 1077     {
6a35c8 1078     while (($pos = strpos($body_lc, '<'.$tag)) && ($pos2 = strpos($body_lc, '</'.$tag.'>', $pos)))
T 1079       {
1080       $pos2 += 8;
1081       $body = substr($body, 0, $pos) . substr($body, $pos2, strlen($body)-$pos2);
1082       $body_lc = strtolower($body);
1083       }
4e17e6 1084     }
6a35c8 1085
T 1086   // replace event handlers on any object
1087   $body = preg_replace('/\s(on[a-z]+)=/im', ' __removed=', $body);  
4e17e6 1088
T 1089   // resolve <base href>
1090   $base_reg = '/(<base.*href=["\']?)([hftps]{3,5}:\/{2}[^"\'\s]+)([^<]*>)/i';
1091   if (preg_match($base_reg, $body, $regs))
1092     {
1093     $base_url = $regs[2];
1094     $body = preg_replace('/(src|background|href)=(["\']?)([\.\/]+[^"\'\s]+)(\2|\s|>)/Uie', "'\\1=\"'.make_absolute_url('\\3', '$base_url').'\"'", $body);
1095     $body = preg_replace('/(url\s*\()(["\']?)([\.\/]+[^"\'\)\s]+)(\2)\)/Uie', "'\\1\''.make_absolute_url('\\3', '$base_url').'\')'", $body);
1096     $body = preg_replace($base_reg, '', $body);
1097     }
1098
1099   // add comments arround html and other tags
1100   $out = preg_replace(array('/(<\/?html[^>]*>)/i',
1101                             '/(<\/?head[^>]*>)/i',
1102                             '/(<title[^>]*>.+<\/title>)/ui',
1103                             '/(<\/?meta[^>]*>)/i'),
1104                       '<!--\\1-->',
1105                       $body);
1106                       
1107   $out = preg_replace(array('/(<body[^>]*>)/i',
1108                             '/(<\/body>)/i'),
1109                       array('<div class="rcmBody">',
1110                             '</div>'),
1111                       $out);
1112
1113   
1114   return $out;
1115   }
1116
1117
1118
1119 // replace all css definitions with #container [def]
1120 function rcmail_mod_css_styles($source, $container_id)
1121   {
1122   $a_css_values = array();
1123   $last_pos = 0;
1124   
1125   // cut out all contents between { and }
1126   while (($pos = strpos($source, '{', $last_pos)) && ($pos2 = strpos($source, '}', $pos)))
1127     {
1128     $key = sizeof($a_css_values);
1129     $a_css_values[$key] = substr($source, $pos+1, $pos2-($pos+1));
1130     $source = substr($source, 0, $pos+1) . "<<str_replacement[$key]>>" . substr($source, $pos2, strlen($source)-$pos2);
1131     $last_pos = $pos+2;
1132     }
1133   
1134   $styles = preg_replace('/(^\s*|,\s*)([a-z0-9\._][a-z0-9\.\-_]*)/im', "\\1#$container_id \\2", $source);
1135   $styles = preg_replace('/<<str_replacement\[([0-9]+)\]>>/e', "\$a_css_values[\\1]", $styles);
1136   
1137   // replace body definition because we also stripped off the <body> tag
1138   $styles = preg_replace("/$container_id\s+body/i", "$container_id div.rcmBody", $styles);
1139   
1140   return $styles;
1141   }
1142
1143
1144
1145 // return first text part of a message
1146 function rcmail_first_text_part($message_parts)
1147   {
1148   if (!is_array($message_parts))
1149     return FALSE;
1150     
1151   $html_part = NULL;
1152       
1153   // check all message parts
1154   foreach ($message_parts as $pid => $part)
1155     {
1156     $mimetype = strtolower($part->ctype_primary.'/'.$part->ctype_secondary);
1157     if ($mimetype=='text/plain')
1158       {
1159       $body = rcube_imap::mime_decode($part->body, $part->headers['content-transfer-encoding']);
1160       $body = rcube_imap::charset_decode($body, $part->ctype_parameters);
1161       return $body;
1162       }
1163     else if ($mimetype=='text/html')
1164       {
1165       $html_part = rcube_imap::mime_decode($part->body, $part->headers['content-transfer-encoding']);
1166       $html_part = rcube_imap::charset_decode($html_part, $part->ctype_parameters);
1167       }
1168     }
1169     
1170
1171   // convert HTML to plain text
1172   if ($html_part)
1173     {    
1174     // remove special chars encoding
1175     $trans = array_flip(get_html_translation_table(HTML_ENTITIES));
1176     $html_part = strtr($html_part, $trans);
1177
1178     // create instance of html2text class
1179     $txt = new html2text($html_part);
1180     return $txt->get_text();
1181     }
1182
1183   return FALSE;
1184   }
1185
1186
1187 // get source code of a specific message and cache it
1188 function rcmail_message_source($uid)
1189   {
1cded8 1190   global $IMAP, $DB, $CONFIG;
4e17e6 1191
1cded8 1192   // get message ID if uid is given
T 1193   $cache_key = $IMAP->mailbox.'.msg';
1194   $cached = $IMAP->get_cached_message($cache_key, $uid, FALSE);
1195   
1196   // message is cached in database
1197   if ($cached && !empty($cached->body))
1198     return $cached->body;
1199
1200   if (!$cached)
1201     $headers = $IMAP->get_headers($uid);
1202   else
1203     $headers = &$cached;
1204
749b07 1205   // create unique identifier based on message_id
T 1206   if (!empty($headers->messageID))
1207     $message_id = md5($headers->messageID);
1208   else
1209     $message_id = md5($headers->uid.'@'.$_SESSION['imap_host']);
4e17e6 1210   
1cded8 1211   $temp_dir = $CONFIG['temp_dir'].(!eregi('\/$', $CONFIG['temp_dir']) ? '/' : '');
T 1212   $cache_dir = $temp_dir.$_SESSION['client_id'];
1213   $cache_path = $cache_dir.'/'.$message_id;
4e17e6 1214
1cded8 1215   // message is cached in temp dir
749b07 1216   if ($CONFIG['enable_caching'] && is_dir($cache_dir) && is_file($cache_path))
4e17e6 1217     {
1cded8 1218     if ($fp = fopen($cache_path, 'r'))
T 1219       {
1220       $msg_source = fread($fp, filesize($cache_path));
1221       fclose($fp);
1222       return $msg_source;
1223       }
1224     }
1225
1226
1227   // get message from server
1228   $msg_source = $IMAP->get_raw_body($uid);
749b07 1229   
T 1230   // return message source without caching
1231   if (!$CONFIG['enable_caching'])
1232     return $msg_source;
1233
1cded8 1234
T 1235   // let's cache the message body within the database
749b07 1236   if ($cached && ($CONFIG['db_max_length'] -300) > $headers->size)
1cded8 1237     {
T 1238     $DB->query("UPDATE ".get_table_name('messages')."
1239                 SET    body=?
1240                 WHERE  user_id=?
1241                 AND    cache_key=?
1242                 AND    uid=?",
1243                $msg_source,
1244                $_SESSION['user_id'],
1245                $cache_key,
1246                $uid);
1247
1248     return $msg_source;
1249     }
1250
1251
1252   // create dir for caching
1253   if (!is_dir($cache_dir))
1254     $dir = mkdir($cache_dir);
1255   else
1256     $dir = true;
1257
1258   // attempt to write a file with the message body    
1259   if ($dir && ($fp = fopen($cache_path, 'w')))
1260     {
1261     fwrite($fp, $msg_source);
1262     fclose($fp);
1263     }
1264   else
1265     {
1266     raise_error(array('code' => 403, 'type' => 'php', 'line' => __LINE__, 'file' => __FILE__, 
1267                       'message' => "Failed to write to temp dir"), TRUE, FALSE);
4e17e6 1268     }
T 1269
1270   return $msg_source;
1271   }
1272
1273
1274 // decode address string and re-format it as HTML links
1275 function rcmail_address_string($input, $max=NULL, $addicon=NULL)
1276   {
1277   global $IMAP, $PRINT_MODE, $CONFIG, $OUTPUT, $JS_OBJECT_NAME, $EMAIL_ADDRESS_PATTERN;
1278   
1279   $a_parts = $IMAP->decode_address_list($input);
1280
1281   if (!sizeof($a_parts))
1282     return $input;
1283
1284   $c = count($a_parts);
1285   $j = 0;
1286   $out = '';
1287
1288   foreach ($a_parts as $part)
1289     {
1290     $j++;
1291     if ($PRINT_MODE)
a95e0e 1292       $out .= sprintf('%s &lt;%s&gt;', rep_specialchars_output($part['name']), $part['mailto']);
4e17e6 1293     else if (preg_match($EMAIL_ADDRESS_PATTERN, $part['mailto']))
T 1294       {
1295       $out .= sprintf('<a href="mailto:%s" onclick="return %s.command(\'compose\',\'%s\',this)" class="rcmContactAddress" title="%s">%s</a>',
1296                       $part['mailto'],
1297                       $JS_OBJECT_NAME,
1298                       $part['mailto'],
1299                       $part['mailto'],
a95e0e 1300                       rep_specialchars_output($part['name']));
4e17e6 1301                       
T 1302       if ($addicon)
1303         $out .= sprintf('&nbsp;<a href="#add" onclick="return %s.command(\'add-contact\',\'%s\',this)" title="%s"><img src="%s%s" alt="add" border="0" /></a>',
1304                         $JS_OBJECT_NAME,
1305                         urlencode($part['string']),
1306                         rcube_label('addtoaddressbook'),
1307                         $CONFIG['skin_path'],
1308                         $addicon);
1309       }
1310     else
1311       {
1312       if ($part['name'])
a95e0e 1313         $out .= rep_specialchars_output($part['name']);
4e17e6 1314       if ($part['mailto'])
T 1315         $out .= (strlen($out) ? ' ' : '') . sprintf('&lt;%s&gt;', $part['mailto']);
1316       }
1317       
1318     if ($c>$j)
1319       $out .= ','.($max ? '&nbsp;' : ' ');
1320         
1321     if ($max && $j==$max && $c>$j)
1322       {
1323       $out .= '...';
1324       break;
1325       }        
1326     }
1327     
1328   return $out;
1329   }
1330
1331
1332 function rcmail_message_part_controls()
1333   {
1334   global $CONFIG, $IMAP, $MESSAGE;
1335   
1336   if (!is_array($MESSAGE) || !is_array($MESSAGE['parts']) || !($_GET['_uid'] && $_GET['_part']) || !$MESSAGE['parts'][$_GET['_part']])
1337     return '';
1338     
1339   $part = $MESSAGE['parts'][$_GET['_part']];
1340   
1341   $attrib_str = create_attrib_string($attrib, array('id', 'class', 'style', 'cellspacing', 'cellpadding', 'border', 'summary'));
1342   $out = '<table '. $attrib_str . ">\n";
1343   
1344   $filename = $part->d_parameters['filename'] ? $part->d_parameters['filename'] : $part->ctype_parameters['name'];
1345   $filesize = strlen($IMAP->mime_decode($part->body, $part->headers['content-transfer-encoding']));
1346   
1347   if ($filename)
1348     {
1349     $out .= sprintf('<tr><td class="title">%s</td><td>%s</td><td>[<a href="./?%s">%s</a>]</tr>'."\n",
1350                     rcube_label('filename'),
1351                     rep_specialchars_output($filename),
1352                     str_replace('_frame=', '_download=', $_SERVER['QUERY_STRING']),
1353                     rcube_label('download'));
1354     }
1355     
1356   if ($filesize)
1357     $out .= sprintf('<tr><td class="title">%s</td><td>%s</td></tr>'."\n",
1358                     rcube_label('filesize'),
1359                     show_bytes($filesize));
1360   
1361   $out .= "\n</table>";
1362   
1363   return $out;
1364   }
1365
1366
1367
1368 function rcmail_message_part_frame($attrib)
1369   {
1370   global $MESSAGE;
1371   
1372   $part = $MESSAGE['parts'][$_GET['_part']];
1373   $ctype_primary = strtolower($part->ctype_primary);
1374
1375   $attrib['src'] = './?'.str_replace('_frame=', ($ctype_primary=='text' ? '_show=' : '_preload='), $_SERVER['QUERY_STRING']);
1376
1377   $attrib_str = create_attrib_string($attrib, array('id', 'class', 'style', 'src', 'width', 'height'));
1378   $out = '<iframe '. $attrib_str . "></ifame>";
1379     
1380   return $out;
1381   }
1382
1383
597170 1384 // create temp dir for attachments
T 1385 function rcmail_create_compose_tempdir()
1386   {
1387   global $CONFIG;
1388   
1389   if ($_SESSION['compose']['temp_dir'])
1390     return $_SESSION['compose']['temp_dir'];
1391   
1392   if (!empty($CONFIG['temp_dir']))
1393     $temp_dir = $CONFIG['temp_dir'].(!eregi('\/$', $CONFIG['temp_dir']) ? '/' : '').$_SESSION['compose']['id'];
1394
1395   // create temp-dir for uploaded attachments
1396   if (!empty($CONFIG['temp_dir']) && is_writeable($CONFIG['temp_dir']))
1397     {
1398     mkdir($temp_dir);
1399     $_SESSION['compose']['temp_dir'] = $temp_dir;
1400     }
1401
1402   return $_SESSION['compose']['temp_dir'];
1403   }
1404
4e17e6 1405
T 1406 // clear message composing settings
1407 function rcmail_compose_cleanup()
1408   {
1409   if (!isset($_SESSION['compose']))
1410     return;
1411   
1412   // remove attachment files from temp dir
1413   if (is_array($_SESSION['compose']['attachments']))
1414     foreach ($_SESSION['compose']['attachments'] as $attachment)
15a9d1 1415       @unlink($attachment['path']);
4e17e6 1416
T 1417   // kill temp dir
1418   if ($_SESSION['compose']['temp_dir'])
15a9d1 1419     @rmdir($_SESSION['compose']['temp_dir']);
4e17e6 1420   
T 1421   unset($_SESSION['compose']);
1422   }
1423   
1424   
1425 ?>