source: github/program/steps/mail/func.inc @ 04d6304

HEADcourier-fixdev-browser-capabilitiespdorelease-0.6release-0.7release-0.8
Last change on this file since 04d6304 was 04d6304, checked in by svncommit <devs@…>, 6 years ago

If the message is single mime part and non-text, show it as an empty message with an attachment, instead of not displaying anything at all.

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