source: subversion/trunk/roundcubemail/program/steps/mail/func.inc @ 295

Last change on this file since 295 was 295, checked in by cmcnulty, 7 years ago

Rolled back to 289 to fix bug 1483922 - reopens bug 1483918

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