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

Last change on this file since 331 was 331, checked in by thomasb, 7 years ago

Quota display as image

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