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

Last change on this file since 213 was 213, checked in by roundcube, 7 years ago

Check for empty mbox value in session

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