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