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

Last change on this file since 519 was 519, checked in by thomasb, 6 years ago

Fixed bugs #1484276 and #1484300

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 49.2 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 ($mbox = get_input_value('_mbox', RCUBE_INPUT_GPC))
34  {
35  $IMAP->set_mailbox($mbox);
36  $_SESSION['mbox'] = $mbox;
37  }
38
39if (!empty($_GET['_page']))
40  {
41  $IMAP->set_page((int)$_GET['_page']);
42  $_SESSION['page'] = (int)$_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_input_value('_uid', RCUBE_INPUT_GET));
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        if (!$cont) $cont = Q(rcube_label('nosubject'));
454        // firefox/mozilla temporary workaround to pad subject with content so that whitespace in rows responds to drag+drop
455        $cont .= '<img src="./program/blank.gif" height="5" width="1000" alt="" />';
456        }
457      else if ($col=='size')
458        $cont = show_bytes($header->$col);
459      else if ($col=='date')
460        $cont = format_date($header->date); //date('m.d.Y G:i:s', strtotime($header->date));
461      else
462        $cont = Q($header->$col);
463       
464      $out .= '<td class="'.$col.'">' . $cont . "</td>\n";
465      }
466
467    $out .= sprintf("<td class=\"icon\">%s</td>\n", $attach_icon ? sprintf($image_tag, $skin_path, $attach_icon, '') : '');
468    $out .= "</tr>\n";
469   
470    if (sizeof($js_row_arr))
471      $a_js_message_arr[$header->uid] = $js_row_arr;
472    }
473 
474  // complete message table
475  $out .= "</tbody></table>\n";
476 
477 
478  $message_count = $IMAP->messagecount();
479 
480  // set client env
481  $javascript .= sprintf("%s.gui_object('mailcontframe', '%s');\n", $JS_OBJECT_NAME, 'mailcontframe');
482  $javascript .= sprintf("%s.gui_object('messagelist', '%s');\n", $JS_OBJECT_NAME, $attrib['id']);
483  $javascript .= sprintf("%s.set_env('messagecount', %d);\n", $JS_OBJECT_NAME, $message_count);
484  $javascript .= sprintf("%s.set_env('current_page', %d);\n", $JS_OBJECT_NAME, $IMAP->list_page);
485  $javascript .= sprintf("%s.set_env('pagecount', %d);\n", $JS_OBJECT_NAME, ceil($message_count/$IMAP->page_size));
486  $javascript .= sprintf("%s.set_env('sort_col', '%s');\n", $JS_OBJECT_NAME, $sort_col);
487  $javascript .= sprintf("%s.set_env('sort_order', '%s');\n", $JS_OBJECT_NAME, $sort_order);
488 
489  if ($attrib['messageicon'])
490    $javascript .= sprintf("%s.set_env('messageicon', '%s%s');\n", $JS_OBJECT_NAME, $skin_path, $attrib['messageicon']);
491  if ($attrib['deletedicon'])
492    $javascript .= sprintf("%s.set_env('deletedicon', '%s%s');\n", $JS_OBJECT_NAME, $skin_path, $attrib['deletedicon']);
493  if ($attrib['unreadicon'])
494    $javascript .= sprintf("%s.set_env('unreadicon', '%s%s');\n", $JS_OBJECT_NAME, $skin_path, $attrib['unreadicon']);
495  if ($attrib['repliedicon'])
496    $javascript .= sprintf("%s.set_env('repliedicon', '%s%s');\n", $JS_OBJECT_NAME, $skin_path, $attrib['repliedicon']);
497  if ($attrib['attachmenticon'])
498    $javascript .= sprintf("%s.set_env('attachmenticon', '%s%s');\n", $JS_OBJECT_NAME, $skin_path, $attrib['attachmenticon']);
499   
500  $javascript .= sprintf("%s.set_env('messages', %s);", $JS_OBJECT_NAME, array2js($a_js_message_arr));
501 
502  $OUTPUT->add_script($javascript); 
503  $OUTPUT->include_script('list.js');
504 
505  return $out;
506  }
507
508
509
510
511// return javascript commands to add rows to the message list
512function rcmail_js_message_list($a_headers, $insert_top=FALSE)
513  {
514  global $CONFIG, $IMAP;
515
516  $commands = '';
517  $a_show_cols = is_array($CONFIG['list_cols']) ? $CONFIG['list_cols'] : array('subject');
518
519  // show 'to' instead of from in sent messages
520  if (($IMAP->get_mailbox_name()==$CONFIG['sent_mbox'] || $IMAP->get_mailbox_name()==$CONFIG['drafts_mbox'])
521      && ($f = array_search('from', $a_show_cols)) && !array_search('to', $a_show_cols))
522    $a_show_cols[$f] = 'to';
523
524  $commands .= sprintf("this.set_message_coltypes(%s);\n", array2js($a_show_cols));
525
526  // loop through message headers
527  for ($n=0; $a_headers[$n]; $n++)
528    {
529    $header = $a_headers[$n];
530    $a_msg_cols = array();
531    $a_msg_flags = array();
532     
533    // format each col; similar as in rcmail_message_list()
534    foreach ($a_show_cols as $col)
535      {
536      if ($col=='from' || $col=='to')
537        $cont = Q(rcmail_address_string($header->$col, 3), 'show');
538      else if ($col=='subject')
539        {
540        $cont = Q($IMAP->decode_header($header->$col));
541        if (!$cont) $cont = Q(rcube_label('nosubject'));
542        }
543      else if ($col=='size')
544        $cont = show_bytes($header->$col);
545      else if ($col=='date')
546        $cont = format_date($header->date); //date('m.d.Y G:i:s', strtotime($header->date));
547      else
548        $cont = Q($header->$col);
549         
550      $a_msg_cols[$col] = $cont;
551      }
552
553    $a_msg_flags['deleted'] = $header->deleted ? 1 : 0;
554    $a_msg_flags['unread'] = $header->seen ? 0 : 1;
555    $a_msg_flags['replied'] = $header->answered ? 1 : 0;
556    $commands .= sprintf("this.add_message_row(%s, %s, %s, %b, %b);\n",
557                         $header->uid,
558                         array2js($a_msg_cols),
559                         array2js($a_msg_flags),
560                         preg_match("/multipart\/m/i", $header->ctype),
561                         $insert_top);
562    }
563
564  return $commands;
565  }
566
567
568// return an HTML iframe for loading mail content
569function rcmail_messagecontent_frame($attrib)
570  {
571  global $OUTPUT, $JS_OBJECT_NAME;
572 
573  if (empty($attrib['id']))
574    $attrib['id'] = 'rcmailcontentwindow';
575
576  // allow the following attributes to be added to the <iframe> tag
577  $attrib_str = create_attrib_string($attrib, array('id', 'class', 'style', 'src', 'width', 'height', 'frameborder'));
578  $framename = $attrib['id'];
579
580  $out = sprintf('<iframe name="%s"%s></iframe>'."\n",
581         $framename,
582         $attrib_str);
583
584  $OUTPUT->add_script("$JS_OBJECT_NAME.set_env('contentframe', '$framename');");
585
586  return $out;
587  }
588
589// return code for search function
590function rcmail_search_form($attrib)
591  {
592  global $OUTPUT, $JS_OBJECT_NAME;
593
594  // add some labels to client
595  rcube_add_label('searching');
596
597  $attrib['name'] = '_q';
598 
599  if (empty($attrib['id']))
600    $attrib['id'] = 'rcmqsearchbox';
601 
602  $input_q = new textfield($attrib);
603  $out = $input_q->show();
604
605  $OUTPUT->add_script(sprintf("%s.gui_object('qsearchbox', '%s');",
606                              $JS_OBJECT_NAME,
607                              $attrib['id']));
608
609  // add form tag around text field
610  if (empty($attrib['form']))
611    $out = sprintf('<form name="rcmqsearchform" action="./" '.
612                   'onsubmit="%s.command(\'search\');return false" style="display:inline;">%s</form>',
613                   $JS_OBJECT_NAME,
614                   $out);
615
616  return $out;
617  }
618
619
620function rcmail_messagecount_display($attrib)
621  {
622  global $IMAP, $OUTPUT, $JS_OBJECT_NAME;
623 
624  if (!$attrib['id'])
625    $attrib['id'] = 'rcmcountdisplay';
626
627  $OUTPUT->add_script(sprintf("%s.gui_object('countdisplay', '%s');",
628                              $JS_OBJECT_NAME,
629                              $attrib['id']));
630
631  // allow the following attributes to be added to the <span> tag
632  $attrib_str = create_attrib_string($attrib, array('style', 'class', 'id'));
633
634 
635  $out = '<span' . $attrib_str . '>';
636  $out .= rcmail_get_messagecount_text();
637  $out .= '</span>';
638  return $out;
639  }
640
641
642function rcmail_quota_display($attrib)
643  {
644  global $OUTPUT, $JS_OBJECT_NAME, $COMM_PATH;
645
646  if (!$attrib['id'])
647    $attrib['id'] = 'rcmquotadisplay';
648
649  $OUTPUT->add_script(sprintf("%s.gui_object('quotadisplay', '%s');", $JS_OBJECT_NAME, $attrib['id']));
650
651  // allow the following attributes to be added to the <span> tag
652  $attrib_str = create_attrib_string($attrib, array('style', 'class', 'id'));
653
654  $out = '<span' . $attrib_str . '>';
655  $out .= rcmail_quota_content($attrib['display']);
656  $out .= '</span>';
657  return $out;
658  }
659
660
661function rcmail_quota_content($display)
662  {
663  global $IMAP, $COMM_PATH;
664
665  if (!$IMAP->get_capability('QUOTA'))
666    $quota_text = rcube_label('unknown');
667  else if ($quota = $IMAP->get_quota())
668    {
669    $quota_text = sprintf("%s / %s (%.0f%%)",
670                          show_bytes($quota["used"] * 1024),
671                          show_bytes($quota["total"] * 1024),
672                          $quota["percent"]);
673
674    // show quota as image (by Brett Patterson)
675    if ($display == 'image' && function_exists('imagegif'))
676      {
677      $attrib = array('width' => 100, 'height' => 14);
678      $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" />',
679                            $COMM_PATH,
680                            $quota['used'], $quota['total'],
681                            $attrib['width'], $attrib['height'],
682                            $attrib['width'], $attrib['height'],
683                            $quota_text,
684                            show_bytes($quota["used"] * 1024),
685                            show_bytes($quota["total"] * 1024));
686      }
687    }
688  else
689    $quota_text = rcube_label('unlimited');
690
691  return $quota_text;
692  }
693
694
695function rcmail_get_messagecount_text($count=NULL, $page=NULL)
696  {
697  global $IMAP, $MESSAGE;
698 
699  if (isset($MESSAGE['index']))
700    {
701    return rcube_label(array('name' => 'messagenrof',
702                             'vars' => array('nr'  => $MESSAGE['index']+1,
703                                             'count' => $count!==NULL ? $count : $IMAP->messagecount())));
704    }
705
706  if ($page===NULL)
707    $page = $IMAP->list_page;
708   
709  $start_msg = ($page-1) * $IMAP->page_size + 1;
710  $max = $count!==NULL ? $count : $IMAP->messagecount();
711
712  if ($max==0)
713    $out = rcube_label('mailboxempty');
714  else
715    $out = rcube_label(array('name' => 'messagesfromto',
716                              'vars' => array('from'  => $start_msg,
717                                              'to'    => min($max, $start_msg + $IMAP->page_size - 1),
718                                              'count' => $max)));
719
720  return Q($out);
721  }
722
723
724function rcmail_print_body($part, $safe=FALSE, $plain=FALSE)
725  {
726  global $IMAP, $REMOTE_OBJECTS, $JS_OBJECT_NAME;
727 
728  $body = is_array($part->replaces) ? strtr($part->body, $part->replaces) : $part->body;
729
730  // convert html to text/plain
731  if ($part->ctype_secondary=='html' && $plain)
732    {
733    $txt = new html2text($body, false, true);
734    $body = $txt->get_text();
735    $part->ctype_secondary = 'plain';
736    }
737   
738  // text/html
739  if ($part->ctype_secondary=='html')
740    {
741    // remove charset specification in HTML message
742    $body = preg_replace('/charset=[a-z0-9\-]+/i', '', $body);
743
744    if (!$safe)  // remove remote images and scripts
745      {
746      $remote_patterns = array('/<img\s+(.*)src=(["\']?)([hftps]{3,5}:\/{2}[^"\'\s]+)(\2|\s|>)/Ui',
747                               '/(src|background)=(["\']?)([hftps]{3,5}:\/{2}[^"\'\s]+)(\2|\s|>)/Ui',
748                               '/(<base.*href=["\']?)([hftps]{3,5}:\/{2}[^"\'\s]+)([^<]*>)/i',
749                               '/(<link.*href=["\']?)([hftps]{3,5}:\/{2}[^"\'\s]+)([^<]*>)/i',
750                               '/url\s*\(["\']?([hftps]{3,5}:\/{2}[^"\'\s]+)["\']?\)/i',
751                               '/url\s*\(["\']?([\.\/]+[^"\'\s]+)["\']?\)/i',
752                               '/<script.+<\/script>/Umis');
753
754      $remote_replaces = array('<img \\1src=\\2./program/blocked.gif\\4',
755                               '',
756                               '',
757                               '',
758                               'none',
759                               'none',
760                               '');
761     
762      // set flag if message containes remote obejcts that where blocked
763      foreach ($remote_patterns as $pattern)
764        {
765        if (preg_match($pattern, $body))
766          {
767          $REMOTE_OBJECTS = TRUE;
768          break;
769          }
770        }
771
772      $body = preg_replace($remote_patterns, $remote_replaces, $body);
773      }
774
775    return Q($body, 'show', FALSE);
776    }
777
778  // text/enriched
779  if ($part->ctype_secondary=='enriched')
780    {
781    return Q(enriched_to_html($body), 'show');
782    }
783  else
784    {
785    // make links and email-addresses clickable
786    $convert_patterns = $convert_replaces = $replace_strings = array();
787   
788    $url_chars = 'a-z0-9_\-\+\*\$\/&%=@#:;';
789    $url_chars_within = '\?\.~,!';
790
791    $convert_patterns[] = "/([\w]+):\/\/([a-z0-9\-\.]+[a-z]{2,4}([$url_chars$url_chars_within]*[$url_chars])?)/ie";
792    $convert_replaces[] = "rcmail_str_replacement('<a href=\"\\1://\\2\" target=\"_blank\">\\1://\\2</a>', \$replace_strings)";
793
794    $convert_patterns[] = "/([^\/:]|\s)(www\.)([a-z0-9\-]{2,}[a-z]{2,4}([$url_chars$url_chars_within]*[$url_chars])?)/ie";
795    $convert_replaces[] = "rcmail_str_replacement('\\1<a href=\"http://\\2\\3\" target=\"_blank\">\\2\\3</a>', \$replace_strings)";
796   
797    $convert_patterns[] = '/([a-z0-9][a-z0-9\-\.\+\_]*@[a-z0-9]([a-z0-9\-][.]?)*[a-z0-9]\\.[a-z]{2,5})/ie';
798    $convert_replaces[] = "rcmail_str_replacement('<a href=\"mailto:\\1\" onclick=\"return $JS_OBJECT_NAME.command(\'compose\',\'\\1\',this)\">\\1</a>', \$replace_strings)";
799   
800    if ($part->ctype_parameters['format'] != 'flowed')
801      $body = wordwrap(trim($body), 80);
802
803    $body = preg_replace($convert_patterns, $convert_replaces, $body);
804
805    // split body into single lines
806    $a_lines = preg_split('/\r?\n/', $body);
807    $quote_level = 0;
808
809    // colorize quoted parts
810    for($n=0; $n<sizeof($a_lines); $n++)
811      {
812      $line = $a_lines[$n];
813      $quotation = '';
814      $q = 0;
815     
816      if (preg_match('/^(>+\s*)/', $line, $regs))
817        {
818        $q = strlen(preg_replace('/\s/', '', $regs[1]));
819        $line = substr($line, strlen($regs[1]));
820
821        if ($q > $quote_level)
822          $quotation = str_repeat('<blockquote>', $q - $quote_level);
823        else if ($q < $quote_level)
824          $quotation = str_repeat("</blockquote>", $quote_level - $q);
825        }
826      else if ($quote_level > 0)
827        $quotation = str_repeat("</blockquote>", $quote_level);
828
829      $quote_level = $q;
830      $a_lines[$n] = $quotation . Q($line, 'replace', FALSE);
831      }
832
833    // insert the links for urls and mailtos
834    $body = preg_replace("/##string_replacement\{([0-9]+)\}##/e", "\$replace_strings[\\1]", join("\n", $a_lines));
835   
836    return "<div class=\"pre\">".$body."\n</div>";
837    }
838  }
839
840
841
842// add a string to the replacement array and return a replacement string
843function rcmail_str_replacement($str, &$rep)
844  {
845  static $count = 0;
846  $rep[$count] = stripslashes($str);
847  return "##string_replacement{".($count++)."}##";
848  }
849
850
851function rcmail_parse_message(&$structure, $arg=array(), $recursive=FALSE)
852  {
853  global $IMAP;
854  static $sa_inline_objects = array();
855
856  // arguments are: (bool)$prefer_html, (string)$get_url
857  extract($arg);
858
859  $a_attachments = array();
860  $a_return_parts = array();
861  $out = '';
862
863  $message_ctype_primary = strtolower($structure->ctype_primary);
864  $message_ctype_secondary = strtolower($structure->ctype_secondary);
865
866  // show message headers
867  if ($recursive && is_array($structure->headers) && isset($structure->headers['subject']))
868    {
869    $c = new stdClass;
870    $c->type = 'headers';
871    $c->headers = &$structure->headers;
872    $a_return_parts[] = $c;
873    }
874
875  // print body if message doesn't have multiple parts
876  if ($message_ctype_primary=='text')
877    {
878    $structure->type = 'content';
879    $a_return_parts[] = &$structure;
880    }
881
882  // message contains alternative parts
883  else if ($message_ctype_primary=='multipart' && $message_ctype_secondary=='alternative' && is_array($structure->parts))
884    {
885    // get html/plaintext parts
886    $plain_part = $html_part = $print_part = $related_part = NULL;
887   
888    foreach ($structure->parts as $p => $sub_part)
889      {
890      $sub_ctype_primary = strtolower($sub_part->ctype_primary);
891      $sub_ctype_secondary = strtolower($sub_part->ctype_secondary);
892
893      // check if sub part is
894      if ($sub_ctype_primary=='text' && $sub_ctype_secondary=='plain')
895        $plain_part = $p;
896      else if ($sub_ctype_primary=='text' && $sub_ctype_secondary=='html')
897        $html_part = $p;
898      else if ($sub_ctype_primary=='text' && $sub_ctype_secondary=='enriched')
899        $enriched_part = $p;
900      else if ($sub_ctype_primary=='multipart' && $sub_ctype_secondary=='related')
901        $related_part = $p;
902      }
903
904    // parse related part (alternative part could be in here)
905    if ($related_part!==NULL && $prefer_html)
906      {
907      list($parts, $attachmnts) = rcmail_parse_message($structure->parts[$related_part], $arg, TRUE);
908      $a_return_parts = array_merge($a_return_parts, $parts);
909      $a_attachments = array_merge($a_attachments, $attachmnts);
910      }
911
912    // print html/plain part
913    else if ($html_part!==NULL && $prefer_html)
914      $print_part = &$structure->parts[$html_part];
915    else if ($enriched_part!==NULL)
916      $print_part = &$structure->parts[$enriched_part];
917    else if ($plain_part!==NULL)
918      $print_part = &$structure->parts[$plain_part];
919
920    // show message body
921    if (is_object($print_part))
922      {
923      $print_part->type = 'content';
924      $a_return_parts[] = $print_part;
925      }
926    // show plaintext warning
927    else if ($html_part!==NULL)
928      {
929      $c = new stdClass;
930      $c->type = 'content';
931      $c->body = rcube_label('htmlmessage');
932      $c->ctype_primary = 'text';
933      $c->ctype_secondary = 'plain';
934     
935      $a_return_parts[] = $c;
936      }
937                               
938    // add html part as attachment
939    if ($html_part!==NULL && $structure->parts[$html_part]!==$print_part)
940      {
941      $html_part = &$structure->parts[$html_part];
942      $html_part->filename = rcube_label('htmlmessage');
943      $html_part->mimetype = 'text/html';
944     
945      $a_attachments[] = $html_part;
946      }
947    }
948
949  // message contains multiple parts
950  else if (is_array($structure->parts) && !empty($structure->parts))
951    {
952    for ($i=0; $i<count($structure->parts); $i++)
953      {
954      $mail_part = &$structure->parts[$i];
955      $primary_type = strtolower($mail_part->ctype_primary);
956      $secondary_type = strtolower($mail_part->ctype_secondary);
957
958      // multipart/alternative
959      if ($primary_type=='multipart')
960        {
961        list($parts, $attachmnts) = rcmail_parse_message($mail_part, $arg, TRUE);
962
963        $a_return_parts = array_merge($a_return_parts, $parts);
964        $a_attachments = array_merge($a_attachments, $attachmnts);
965        }
966
967      // part text/[plain|html] OR message/delivery-status
968      else if (($primary_type=='text' && ($secondary_type=='plain' || $secondary_type=='html') && $mail_part->disposition!='attachment') ||
969               ($primary_type=='message' && $secondary_type=='delivery-status'))
970        {
971        $mail_part->type = 'content';
972        $a_return_parts[] = $mail_part;
973        }
974
975      // part message/*
976      else if ($primary_type=='message')
977        {
978        list($parts, $attachmnts) = rcmail_parse_message($mail_part, $arg, TRUE);
979         
980        $a_return_parts = array_merge($a_return_parts, $parts);
981        $a_attachments = array_merge($a_attachments, $attachmnts);
982        }
983
984      // part is file/attachment
985      else if ($mail_part->disposition=='attachment' || $mail_part->disposition=='inline' || $mail_part->headers['content-id'] ||
986               (empty($mail_part->disposition) && $mail_part->filename))
987        {
988        // skip apple resource forks
989        if ($message_ctype_secondary=='appledouble' && $secondary_type=='applefile')
990          continue;
991
992        // part belongs to a related message
993        if ($message_ctype_secondary=='related' && $mail_part->headers['content-id'])
994          {
995          $mail_part->content_id = preg_replace(array('/^</', '/>$/'), '', $mail_part->headers['content-id']);
996          $sa_inline_objects[] = $mail_part;
997          }
998        // is regular attachment
999        else if ($mail_part->filename)
1000          $a_attachments[] = $mail_part;
1001        }
1002      }
1003
1004    // if this was a related part try to resolve references
1005    if ($message_ctype_secondary=='related' && sizeof($sa_inline_objects))
1006      {
1007      $a_replaces = array();
1008       
1009      foreach ($sa_inline_objects as $inline_object)
1010        $a_replaces['cid:'.$inline_object->content_id] = htmlspecialchars(sprintf($get_url, $inline_object->mime_id));
1011     
1012      // add replace array to each content part
1013      // (will be applied later when part body is available)
1014      for ($i=0; $i<count($a_return_parts); $i++)
1015        {
1016        if ($a_return_parts[$i]->type=='content')
1017          $a_return_parts[$i]->replaces = $a_replaces;
1018        }
1019      }
1020    }
1021
1022  // message is single part non-text
1023  else if ($structure->filename)
1024    $a_attachments[] = $structure;
1025
1026  return array($a_return_parts, $a_attachments);
1027  }
1028
1029
1030
1031
1032// return table with message headers
1033function rcmail_message_headers($attrib, $headers=NULL)
1034  {
1035  global $IMAP, $OUTPUT, $MESSAGE;
1036  static $sa_attrib;
1037 
1038  // keep header table attrib
1039  if (is_array($attrib) && !$sa_attrib)
1040    $sa_attrib = $attrib;
1041  else if (!is_array($attrib) && is_array($sa_attrib))
1042    $attrib = $sa_attrib;
1043 
1044 
1045  if (!isset($MESSAGE))
1046    return FALSE;
1047
1048  // get associative array of headers object
1049  if (!$headers)
1050    $headers = is_object($MESSAGE['headers']) ? get_object_vars($MESSAGE['headers']) : $MESSAGE['headers'];
1051   
1052  $header_count = 0;
1053 
1054  // allow the following attributes to be added to the <table> tag
1055  $attrib_str = create_attrib_string($attrib, array('style', 'class', 'id', 'cellpadding', 'cellspacing', 'border', 'summary'));
1056  $out = '<table' . $attrib_str . ">\n";
1057
1058  // show these headers
1059  $standard_headers = array('subject', 'from', 'organization', 'to', 'cc', 'bcc', 'reply-to', 'date');
1060 
1061  foreach ($standard_headers as $hkey)
1062    {
1063    if (!$headers[$hkey])
1064      continue;
1065
1066    if ($hkey=='date' && !empty($headers[$hkey]))
1067      $header_value = format_date(strtotime($headers[$hkey]));
1068    else if (in_array($hkey, array('from', 'to', 'cc', 'bcc', 'reply-to')))
1069      $header_value = Q(rcmail_address_string($headers[$hkey], NULL, $attrib['addicon']), 'show');
1070    else
1071      $header_value = Q($IMAP->decode_header($headers[$hkey]));
1072
1073    $out .= "\n<tr>\n";
1074    $out .= '<td class="header-title">'.Q(rcube_label($hkey)).":&nbsp;</td>\n";
1075    $out .= '<td class="'.$hkey.'" width="90%">'.$header_value."</td>\n</tr>";
1076    $header_count++;
1077    }
1078
1079  $out .= "\n</table>\n\n";
1080
1081  return $header_count ? $out : ''; 
1082  }
1083
1084
1085
1086function rcmail_message_body($attrib)
1087  {
1088  global $CONFIG, $OUTPUT, $MESSAGE, $IMAP, $GET_URL, $REMOTE_OBJECTS, $JS_OBJECT_NAME;
1089 
1090  if (!is_array($MESSAGE['parts']) && !$MESSAGE['body'])
1091    return '';
1092   
1093  if (!$attrib['id'])
1094    $attrib['id'] = 'rcmailMsgBody';
1095
1096  $safe_mode = (bool)$_GET['_safe'];
1097  $attrib_str = create_attrib_string($attrib, array('style', 'class', 'id'));
1098  $out = '<div '. $attrib_str . ">\n";
1099 
1100  $header_attrib = array();
1101  foreach ($attrib as $attr => $value)
1102    if (preg_match('/^headertable([a-z]+)$/i', $attr, $regs))
1103      $header_attrib[$regs[1]] = $value;
1104
1105
1106  // this is an ecrypted message
1107  // -> create a plaintext body with the according message
1108  if (!sizeof($MESSAGE['parts']) && $MESSAGE['headers']->ctype=='multipart/encrypted')
1109    {
1110    $p = new stdClass;
1111    $p->type = 'content';
1112    $p->ctype_primary = 'text';
1113    $p->ctype_secondary = 'plain';
1114    $p->body = rcube_label('encryptedmessage');
1115    $MESSAGE['parts'][0] = $p;
1116    }
1117 
1118  if ($MESSAGE['parts'])
1119    {
1120    foreach ($MESSAGE['parts'] as $i => $part)
1121      {
1122      if ($part->type=='headers')
1123        $out .= rcmail_message_headers(sizeof($header_attrib) ? $header_attrib : NULL, $part->headers);
1124      else if ($part->type=='content')
1125        {
1126        if (empty($part->ctype_parameters) || empty($part->ctype_parameters['charset']))
1127          $part->ctype_parameters['charset'] = $MESSAGE['headers']->charset;
1128
1129        // fetch part if not available
1130        if (!isset($part->body))
1131          $part->body = $IMAP->get_message_part($MESSAGE['UID'], $part->mime_id, $part);
1132
1133        $body = rcmail_print_body($part, $safe_mode, !$CONFIG['prefer_html']);
1134        $out .= '<div class="message-part">';
1135       
1136        if ($part->ctype_secondary != 'plain')
1137          $out .= rcmail_sanitize_html($body, $attrib['id']);
1138        else
1139          $out .= $body;
1140
1141        $out .= "</div>\n";
1142        }
1143      }
1144    }
1145  else
1146    $out .= $MESSAGE['body'];
1147
1148
1149  $ctype_primary = strtolower($MESSAGE['structure']->ctype_primary);
1150  $ctype_secondary = strtolower($MESSAGE['structure']->ctype_secondary);
1151 
1152  // list images after mail body
1153  if (get_boolean($attrib['showimages']) && $ctype_primary=='multipart' && $ctype_secondary=='mixed' &&
1154      sizeof($MESSAGE['attachments']) && !strstr($message_body, '<html') && strlen($GET_URL))
1155    {
1156    foreach ($MESSAGE['attachments'] as $attach_prop)
1157      {
1158      if (strpos($attach_prop->mimetype, 'image/')===0)
1159        $out .= sprintf("\n<hr />\n<p align=\"center\"><img src=\"%s&amp;_part=%s\" alt=\"%s\" title=\"%s\" /></p>\n",
1160                        htmlspecialchars($GET_URL), $attach_prop->mime_id,
1161                        $attach_prop->filename,
1162                        $attach_prop->filename);
1163      }
1164    }
1165 
1166  // tell client that there are blocked remote objects
1167  if ($REMOTE_OBJECTS && !$safe_mode)
1168    $OUTPUT->add_script(sprintf("%s.set_env('blockedobjects', true);", $JS_OBJECT_NAME));
1169
1170  $out .= "\n</div>";
1171  return $out;
1172  }
1173
1174
1175
1176// modify a HTML message that it can be displayed inside a HTML page
1177function rcmail_sanitize_html($body, $container_id)
1178  {
1179  // remove any null-byte characters before parsing
1180  $body = preg_replace('/\x00/', '', $body);
1181 
1182  $last_style_pos = 0;
1183  $body_lc = strtolower($body);
1184 
1185  // find STYLE tags
1186  while (($pos = strpos($body_lc, '<style', $last_style_pos)) && ($pos2 = strpos($body_lc, '</style>', $pos)))
1187    {
1188    $pos = strpos($body_lc, '>', $pos)+1;
1189
1190    // replace all css definitions with #container [def]
1191    $styles = rcmail_mod_css_styles(substr($body, $pos, $pos2-$pos), $container_id);
1192
1193    $body = substr($body, 0, $pos) . $styles . substr($body, $pos2);
1194    $body_lc = strtolower($body);
1195    $last_style_pos = $pos2;
1196    }
1197
1198
1199  // remove SCRIPT tags
1200  foreach (array('script', 'applet', 'object', 'embed', 'iframe') as $tag)
1201    {
1202    while (($pos = strpos($body_lc, '<'.$tag)) && ($pos2 = strpos($body_lc, '</'.$tag.'>', $pos)))
1203      {
1204      $pos2 += strlen('</'.$tag.'>');
1205      $body = substr($body, 0, $pos) . substr($body, $pos2, strlen($body)-$pos2);
1206      $body_lc = strtolower($body);
1207      }
1208    }
1209
1210  // replace event handlers on any object
1211  while ($body != $prev_body)
1212    {
1213    $prev_body = $body;
1214    $body = preg_replace('/(<[^!][^>]*\s)(on[^=>]+)=([^>]+>)/im', '$1__removed=$3', $body);
1215    $body = preg_replace('/(<[^!][^>]*\shref=["\']?)(javascript:)([^>]*?>)/im', '$1null:$3', $body);
1216    }
1217
1218  // resolve <base href>
1219  $base_reg = '/(<base.*href=["\']?)([hftps]{3,5}:\/{2}[^"\'\s]+)([^<]*>)/i';
1220  if (preg_match($base_reg, $body, $regs))
1221    {
1222    $base_url = $regs[2];
1223    $body = preg_replace('/(src|background|href)=(["\']?)([\.\/]+[^"\'\s]+)(\2|\s|>)/Uie', "'\\1=\"'.make_absolute_url('\\3', '$base_url').'\"'", $body);
1224    $body = preg_replace('/(url\s*\()(["\']?)([\.\/]+[^"\'\)\s]+)(\2)\)/Uie', "'\\1\''.make_absolute_url('\\3', '$base_url').'\')'", $body);
1225    $body = preg_replace($base_reg, '', $body);
1226    }
1227   
1228  // modify HTML links to open a new window if clicked
1229  $body = preg_replace('/<a\s+([^>]+)>/Uie', "rcmail_alter_html_link('\\1');", $body);
1230
1231  // add comments arround html and other tags
1232  $out = preg_replace(array('/(<\/?html[^>]*>)/i',
1233                            '/(<\/?head[^>]*>)/i',
1234                            '/(<title[^>]*>.*<\/title>)/Ui',
1235                            '/(<\/?meta[^>]*>)/i'),
1236                      '<!--\\1-->',
1237                      $body);
1238
1239  $out = preg_replace(array('/(<body[^>]*>)/i',
1240                            '/(<\/body>)/i'),
1241                      array('<div class="rcmBody">',
1242                            '</div>'),
1243                      $out);
1244
1245  // quote <? of php and xml files that are specified as text/html
1246  $out = preg_replace(array('/<\?/', '/\?>/'), array('&lt;?', '?&gt;'), $out);
1247
1248  return $out;
1249  }
1250
1251
1252// parse link attributes and set correct target
1253function rcmail_alter_html_link($in)
1254  {
1255  $in = preg_replace('/=([^("|\'|\s)]+)(\s|$)/', '="\1"', $in);
1256  $attrib = parse_attrib_string($in);
1257
1258  if (stristr((string)$attrib['href'], 'mailto:'))
1259    $attrib['onclick'] = sprintf("return %s.command('compose','%s',this)",
1260                                 $GLOBALS['JS_OBJECT_NAME'],
1261                                 JQ(substr($attrib['href'], 7)));
1262  else if (!empty($attrib['href']) && $attrib['href']{0}!='#')
1263    $attrib['target'] = '_blank';
1264 
1265  return '<a' . create_attrib_string($attrib, array('href', 'name', 'target', 'onclick', 'id', 'class', 'style', 'title')) . '>';
1266  }
1267
1268
1269// replace all css definitions with #container [def]
1270function rcmail_mod_css_styles($source, $container_id)
1271  {
1272  $a_css_values = array();
1273  $last_pos = 0;
1274 
1275  // cut out all contents between { and }
1276  while (($pos = strpos($source, '{', $last_pos)) && ($pos2 = strpos($source, '}', $pos)))
1277    {
1278    $key = sizeof($a_css_values);
1279    $a_css_values[$key] = substr($source, $pos+1, $pos2-($pos+1));
1280    $source = substr($source, 0, $pos+1) . "<<str_replacement[$key]>>" . substr($source, $pos2, strlen($source)-$pos2);
1281    $last_pos = $pos+2;
1282    }
1283
1284  // remove html commends and add #container to each tag selector.
1285  // also replace body definition because we also stripped off the <body> tag
1286  $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"),
1287                         array('', "\\1#$container_id \\2", "\$a_css_values[\\1]", "$container_id div.rcmBody"),
1288                         $source);
1289
1290  return $styles;
1291  }
1292
1293
1294function rcmail_has_html_part($message_parts)
1295{
1296   if (!is_array($message_parts))
1297      return FALSE;
1298
1299   // check all message parts
1300   foreach ($message_parts as $pid => $part)
1301   {
1302      $mimetype = strtolower($part->ctype_primary.'/'.$part->ctype_secondary);
1303      if ($mimetype=='text/html')
1304      {
1305         return TRUE;
1306      }
1307   }
1308   
1309   return FALSE;
1310}
1311
1312// return first HTML part of a message
1313function rcmail_first_html_part($message_struct)
1314  {
1315  global $IMAP;
1316
1317  if (!is_array($message_struct['parts']))
1318    return FALSE;
1319   
1320  $html_part = NULL;
1321
1322  // check all message parts
1323  foreach ($message_struct['parts'] as $pid => $part)
1324    {
1325    $mimetype = strtolower($part->ctype_primary.'/'.$part->ctype_secondary);
1326    if ($mimetype=='text/html')
1327      {
1328      $html_part = $IMAP->get_message_part($message_struct['UID'], $pid, $part);
1329      }
1330    }
1331
1332  if ($html_part)
1333    {
1334    // remove special chars encoding
1335    //$trans = array_flip(get_html_translation_table(HTML_ENTITIES));
1336    //$html_part = strtr($html_part, $trans);
1337
1338    return $html_part;
1339    }
1340
1341  return FALSE;
1342}
1343
1344
1345// return first text part of a message
1346function rcmail_first_text_part($message_struct)
1347  {
1348  global $IMAP;
1349
1350  if (empty($message_struct['parts']))
1351    return $message_struct['UID'] ? $IMAP->get_body($message_struct['UID']) : false;
1352
1353  // check all message parts
1354  foreach ($message_struct['parts'] as $pid => $part)
1355    {
1356    $mimetype = strtolower($part->ctype_primary.'/'.$part->ctype_secondary);
1357
1358    if ($mimetype=='text/plain')
1359      return $IMAP->get_message_part($message_struct['UID'], $pid, $part);
1360
1361    else if ($mimetype=='text/html')
1362      {
1363      $html_part = $IMAP->get_message_part($message_struct['UID'], $pid, $part);
1364     
1365      // remove special chars encoding
1366      $trans = array_flip(get_html_translation_table(HTML_ENTITIES));
1367      $html_part = strtr($html_part, $trans);
1368
1369      // create instance of html2text class
1370      $txt = new html2text($html_part);
1371      return $txt->get_text();
1372      }
1373    }
1374
1375  return FALSE;
1376  }
1377
1378
1379// decode address string and re-format it as HTML links
1380function rcmail_address_string($input, $max=NULL, $addicon=NULL)
1381  {
1382  global $IMAP, $PRINT_MODE, $CONFIG, $OUTPUT, $JS_OBJECT_NAME, $EMAIL_ADDRESS_PATTERN;
1383 
1384  $a_parts = $IMAP->decode_address_list($input);
1385
1386  if (!sizeof($a_parts))
1387    return $input;
1388
1389  $c = count($a_parts);
1390  $j = 0;
1391  $out = '';
1392
1393  foreach ($a_parts as $part)
1394    {
1395    $j++;
1396    if ($PRINT_MODE)
1397      $out .= sprintf('%s &lt;%s&gt;', Q($part['name']), $part['mailto']);
1398    else if (preg_match($EMAIL_ADDRESS_PATTERN, $part['mailto']))
1399      {
1400      $out .= sprintf('<a href="mailto:%s" onclick="return %s.command(\'compose\',\'%s\',this)" class="rcmContactAddress" title="%s">%s</a>',
1401                      Q($part['mailto']),
1402                      $JS_OBJECT_NAME,
1403                      JQ($part['mailto']),
1404                      Q($part['mailto']),
1405                      Q($part['name']));
1406                     
1407      if ($addicon)
1408        $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>',
1409                        $JS_OBJECT_NAME,
1410                        urlencode($part['string']),
1411                        rcube_label('addtoaddressbook'),
1412                        $CONFIG['skin_path'],
1413                        $addicon);
1414      }
1415    else
1416      {
1417      if ($part['name'])
1418        $out .= Q($part['name']);
1419      if ($part['mailto'])
1420        $out .= (strlen($out) ? ' ' : '') . sprintf('&lt;%s&gt;', Q($part['mailto']));
1421      }
1422     
1423    if ($c>$j)
1424      $out .= ','.($max ? '&nbsp;' : ' ');
1425       
1426    if ($max && $j==$max && $c>$j)
1427      {
1428      $out .= '...';
1429      break;
1430      }       
1431    }
1432   
1433  return $out;
1434  }
1435
1436
1437function rcmail_message_part_controls()
1438  {
1439  global $CONFIG, $IMAP, $MESSAGE;
1440 
1441  if (!is_array($MESSAGE) || !is_array($MESSAGE['parts']) || !($_GET['_uid'] && $_GET['_part']) || !$MESSAGE['parts'][$_GET['_part']])
1442    return '';
1443   
1444  $part = &$MESSAGE['parts'][$_GET['_part']];
1445 
1446  $attrib_str = create_attrib_string($attrib, array('id', 'class', 'style', 'cellspacing', 'cellpadding', 'border', 'summary'));
1447  $out = '<table '. $attrib_str . ">\n";
1448 
1449  if ($filename)
1450    {
1451    $out .= sprintf('<tr><td class="title">%s</td><td>%s</td><td>[<a href="./?%s">%s</a>]</tr>'."\n",
1452                    Q(rcube_label('filename')),
1453                    Q($part->filename),
1454                    str_replace('_frame=', '_download=', $_SERVER['QUERY_STRING']),
1455                    Q(rcube_label('download')));
1456    }
1457   
1458  if ($part->size)
1459    $out .= sprintf('<tr><td class="title">%s</td><td>%s</td></tr>'."\n",
1460                    Q(rcube_label('filesize')),
1461                    show_bytes($part->size));
1462 
1463  $out .= "\n</table>";
1464 
1465  return $out;
1466  }
1467
1468
1469
1470function rcmail_message_part_frame($attrib)
1471  {
1472  global $MESSAGE;
1473 
1474  $part = $MESSAGE['parts'][$_GET['_part']];
1475  $ctype_primary = strtolower($part->ctype_primary);
1476
1477  $attrib['src'] = './?'.str_replace('_frame=', ($ctype_primary=='text' ? '_show=' : '_preload='), $_SERVER['QUERY_STRING']);
1478
1479  $attrib_str = create_attrib_string($attrib, array('id', 'class', 'style', 'src', 'width', 'height'));
1480  $out = '<iframe '. $attrib_str . "></iframe>";
1481   
1482  return $out;
1483  }
1484
1485
1486// clear message composing settings
1487function rcmail_compose_cleanup()
1488  {
1489  if (!isset($_SESSION['compose']))
1490    return;
1491
1492  // remove attachment files from temp dir
1493  if (is_array($_SESSION['compose']['attachments']))
1494    foreach ($_SESSION['compose']['attachments'] as $attachment)
1495      @unlink($attachment['path']);
1496 
1497  unset($_SESSION['compose']);
1498  }
1499 
1500 
1501?>
Note: See TracBrowser for help on using the repository browser.