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

Last change on this file since 451 was 451, checked in by estadtherr, 6 years ago

fixed display of HTML attachments

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