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

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

Improved contacts drop down; HTML output improvements; JS code cleanup

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 49.8 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  // text/html
731  if ($part->ctype_secondary=='html')
732    {
733    // remove charset specification in HTML message
734    $body = preg_replace('/charset=[a-z0-9\-]+/i', '', $body);
735
736    if (!$safe)  // remove remote images and scripts
737      {
738      $remote_patterns = array('/<img\s+(.*)src=(["\']?)([hftps]{3,5}:\/{2}[^"\'\s]+)(\2|\s|>)/Ui',
739                               '/(src|background)=(["\']?)([hftps]{3,5}:\/{2}[^"\'\s]+)(\2|\s|>)/Ui',
740                               '/(<base.*href=["\']?)([hftps]{3,5}:\/{2}[^"\'\s]+)([^<]*>)/i',
741                               '/(<link.*href=["\']?)([hftps]{3,5}:\/{2}[^"\'\s]+)([^<]*>)/i',
742                               '/url\s*\(["\']?([hftps]{3,5}:\/{2}[^"\'\s]+)["\']?\)/i',
743                               '/url\s*\(["\']?([\.\/]+[^"\'\s]+)["\']?\)/i',
744                               '/<script.+<\/script>/Umis');
745
746      $remote_replaces = array('<img \\1src=\\2./program/blocked.gif\\4',
747                               '',
748                               '',
749                               '',
750                               'none',
751                               'none',
752                               '');
753     
754      // set flag if message containes remote obejcts that where blocked
755      foreach ($remote_patterns as $pattern)
756        {
757        if (preg_match($pattern, $body))
758          {
759          $REMOTE_OBJECTS = TRUE;
760          break;
761          }
762        }
763
764      $body = preg_replace($remote_patterns, $remote_replaces, $body);
765      }
766
767    return Q($body, 'show', FALSE);
768    }
769
770  // text/enriched
771  if ($part->ctype_secondary=='enriched')
772    {
773    return Q(enriched_to_html($body), 'show');
774    }
775  else
776    {
777    // make links and email-addresses clickable
778    $convert_patterns = $convert_replaces = $replace_strings = array();
779   
780    $url_chars = 'a-z0-9_\-\+\*\$\/&%=@#:;';
781    $url_chars_within = '\?\.~,!';
782
783    $convert_patterns[] = "/([\w]+):\/\/([a-z0-9\-\.]+[a-z]{2,4}([$url_chars$url_chars_within]*[$url_chars])?)/ie";
784    $convert_replaces[] = "rcmail_str_replacement('<a href=\"\\1://\\2\" target=\"_blank\">\\1://\\2</a>', \$replace_strings)";
785
786    $convert_patterns[] = "/([^\/:]|\s)(www\.)([a-z0-9\-]{2,}[a-z]{2,4}([$url_chars$url_chars_within]*[$url_chars])?)/ie";
787    $convert_replaces[] = "rcmail_str_replacement('\\1<a href=\"http://\\2\\3\" target=\"_blank\">\\2\\3</a>', \$replace_strings)";
788   
789    $convert_patterns[] = '/([a-z0-9][a-z0-9\-\.\+\_]*@[a-z0-9]([a-z0-9\-][.]?)*[a-z0-9]\\.[a-z]{2,5})/ie';
790    $convert_replaces[] = "rcmail_str_replacement('<a href=\"mailto:\\1\" onclick=\"return $JS_OBJECT_NAME.command(\'compose\',\'\\1\',this)\">\\1</a>', \$replace_strings)";
791   
792    if ($part->ctype_parameters['format'] != 'flowed')
793      $body = wordwrap(trim($body), 80);
794
795    $body = preg_replace($convert_patterns, $convert_replaces, $body);
796
797    // split body into single lines
798    $a_lines = preg_split('/\r?\n/', $body);
799    $quote_level = 0;
800
801    // colorize quoted parts
802    for($n=0; $n<sizeof($a_lines); $n++)
803      {
804      $line = $a_lines[$n];
805      $quotation = '';
806      $q = 0;
807     
808      if (preg_match('/^(>+\s*)/', $line, $regs))
809        {
810        $q = strlen(preg_replace('/\s/', '', $regs[1]));
811        $line = substr($line, strlen($regs[1]));
812
813        if ($q > $quote_level)
814          $quotation = str_repeat('<blockquote>', $q - $quote_level);
815        else if ($q < $quote_level)
816          $quotation = str_repeat("</blockquote>", $quote_level - $q);
817        }
818      else if ($quote_level > 0)
819        $quotation = str_repeat("</blockquote>", $quote_level);
820
821      $quote_level = $q;
822      $a_lines[$n] = $quotation . Q($line, 'replace', FALSE);
823      }
824
825    // insert the links for urls and mailtos
826    $body = preg_replace("/##string_replacement\{([0-9]+)\}##/e", "\$replace_strings[\\1]", join("\n", $a_lines));
827   
828    return "<div class=\"pre\">".$body."\n</div>";
829    }
830  }
831
832
833
834// add a string to the replacement array and return a replacement string
835function rcmail_str_replacement($str, &$rep)
836  {
837  static $count = 0;
838  $rep[$count] = stripslashes($str);
839  return "##string_replacement{".($count++)."}##";
840  }
841
842
843function rcmail_parse_message(&$structure, $arg=array(), $recursive=FALSE)
844  {
845  global $IMAP;
846  static $sa_inline_objects = array();
847
848  // arguments are: (bool)$prefer_html, (string)$get_url
849  extract($arg);
850
851  $a_attachments = array();
852  $a_return_parts = array();
853  $out = '';
854
855  $message_ctype_primary = strtolower($structure->ctype_primary);
856  $message_ctype_secondary = strtolower($structure->ctype_secondary);
857
858  // show message headers
859  if ($recursive && is_array($structure->headers) && isset($structure->headers['subject']))
860    {
861    $c = new stdClass;
862    $c->type = 'headers';
863    $c->headers = &$structure->headers;
864    $a_return_parts[] = $c;
865    }
866
867  // print body if message doesn't have multiple parts
868  if ($message_ctype_primary=='text')
869    {
870    $structure->type = 'content';
871    $a_return_parts[] = &$structure;
872    }
873
874  // message contains alternative parts
875  else if ($message_ctype_primary=='multipart' && $message_ctype_secondary=='alternative' && is_array($structure->parts))
876    {
877    // get html/plaintext parts
878    $plain_part = $html_part = $print_part = $related_part = NULL;
879   
880    foreach ($structure->parts as $p => $sub_part)
881      {
882      $sub_ctype_primary = strtolower($sub_part->ctype_primary);
883      $sub_ctype_secondary = strtolower($sub_part->ctype_secondary);
884
885      // check if sub part is
886      if ($sub_ctype_primary=='text' && $sub_ctype_secondary=='plain')
887        $plain_part = $p;
888      else if ($sub_ctype_primary=='text' && $sub_ctype_secondary=='html')
889        $html_part = $p;
890      else if ($sub_ctype_primary=='text' && $sub_ctype_secondary=='enriched')
891        $enriched_part = $p;
892      else if ($sub_ctype_primary=='multipart' && $sub_ctype_secondary=='related')
893        $related_part = $p;
894      }
895
896    // parse related part (alternative part could be in here)
897    if ($related_part!==NULL && $prefer_html)
898      {
899      list($parts, $attachmnts) = rcmail_parse_message($structure->parts[$related_part], $arg, TRUE);
900      $a_return_parts = array_merge($a_return_parts, $parts);
901      $a_attachments = array_merge($a_attachments, $attachmnts);
902      }
903
904    // print html/plain part
905    else if ($html_part!==NULL && $prefer_html)
906      $print_part = &$structure->parts[$html_part];
907    else if ($enriched_part!==NULL)
908      $print_part = &$structure->parts[$enriched_part];
909    else if ($plain_part!==NULL)
910      $print_part = &$structure->parts[$plain_part];
911
912    // show message body
913    if (is_object($print_part))
914      {
915      $print_part->type = 'content';
916      $a_return_parts[] = $print_part;
917      }
918    // show plaintext warning
919    else if ($html_part!==NULL)
920      {
921      $c = new stdClass;
922      $c->type = 'content';
923      $c->body = rcube_label('htmlmessage');
924      $c->ctype_primary = 'text';
925      $c->ctype_secondary = 'plain';
926     
927      $a_return_parts[] = $c;
928      }
929                               
930    // add html part as attachment
931    if ($html_part!==NULL && $structure->parts[$html_part]!==$print_part)
932      {
933      $html_part = &$structure->parts[$html_part];
934      $html_part->filename = rcube_label('htmlmessage');
935      $html_part->mimetype = 'text/html';
936     
937      $a_attachments[] = $html_part;
938      }
939    }
940
941  // message contains multiple parts
942  else if (is_array($structure->parts) && !empty($structure->parts))
943    {
944    for ($i=0; $i<count($structure->parts); $i++)
945      {
946      $mail_part = &$structure->parts[$i];
947      $primary_type = strtolower($mail_part->ctype_primary);
948      $secondary_type = strtolower($mail_part->ctype_secondary);
949
950      // multipart/alternative
951      if ($primary_type=='multipart')
952        {
953        list($parts, $attachmnts) = rcmail_parse_message($mail_part, $arg, TRUE);
954
955        $a_return_parts = array_merge($a_return_parts, $parts);
956        $a_attachments = array_merge($a_attachments, $attachmnts);
957        }
958
959      // part text/[plain|html] OR message/delivery-status
960      else if (($primary_type=='text' && ($secondary_type=='plain' || $secondary_type=='html') && $mail_part->disposition!='attachment') ||
961               ($primary_type=='message' && $secondary_type=='delivery-status'))
962        {
963        $mail_part->type = 'content';
964        $a_return_parts[] = $mail_part;
965        }
966
967      // part message/*
968      else if ($primary_type=='message')
969        {
970        list($parts, $attachmnts) = rcmail_parse_message($mail_part, $arg, TRUE);
971         
972        $a_return_parts = array_merge($a_return_parts, $parts);
973        $a_attachments = array_merge($a_attachments, $attachmnts);
974        }
975
976      // part is file/attachment
977      else if ($mail_part->disposition=='attachment' || $mail_part->disposition=='inline' || $mail_part->headers['content-id'] ||
978               (empty($mail_part->disposition) && ($mail_part->d_parameters['filename'] || $mail_part->ctype_parameters['name'])))
979        {
980        // skip apple resource forks
981        if ($message_ctype_secondary=='appledouble' && $secondary_type=='applefile')
982          continue;
983
984        // part belongs to a related message
985        if ($message_ctype_secondary=='related' && $mail_part->headers['content-id'])
986          {
987          $mail_part->filename = rcube_imap::decode_mime_string($mail_part->d_parameters['filename']);
988          $mail_part->content_id = preg_replace(array('/^</', '/>$/'), '', $mail_part->headers['content-id']);
989          $sa_inline_objects[] = $mail_part;
990          }
991        // is regular attachment
992        else if (($fname = $mail_part->d_parameters['filename']) ||
993                 ($fname = $mail_part->ctype_parameters['name']) ||
994                 ($fname = $mail_part->headers['content-description']))
995          {
996          $mail_part->filename = rcube_imap::decode_mime_string($fname);
997          $a_attachments[] = $mail_part;
998          }
999        }
1000      }
1001
1002    // if this was a related part try to resolve references
1003    if ($message_ctype_secondary=='related' && sizeof($sa_inline_objects))
1004      {
1005      $a_replaces = array();
1006       
1007      foreach ($sa_inline_objects as $inline_object)
1008        $a_replaces['cid:'.$inline_object->content_id] = htmlspecialchars(sprintf($get_url, $inline_object->mime_id));
1009     
1010      // add replace array to each content part
1011      // (will be applied later when part body is available)
1012      for ($i=0; $i<count($a_return_parts); $i++)
1013        {
1014        if ($a_return_parts[$i]->type=='content')
1015          $a_return_parts[$i]->replaces = $a_replaces;
1016        }
1017      }
1018    }
1019
1020  // message is single part non-text
1021  else
1022    {
1023    if (($fname = $structure->d_parameters['filename']) ||
1024        ($fname = $structure->ctype_parameters['name']) ||
1025        ($fname = $structure->headers['content-description']))
1026      {
1027      $structure->filename = rcube_imap::decode_mime_string($fname);
1028      $a_attachments[] = $structure;
1029      }
1030    }
1031
1032  return array($a_return_parts, $a_attachments);
1033  }
1034
1035
1036
1037
1038// return table with message headers
1039function rcmail_message_headers($attrib, $headers=NULL)
1040  {
1041  global $IMAP, $OUTPUT, $MESSAGE;
1042  static $sa_attrib;
1043 
1044  // keep header table attrib
1045  if (is_array($attrib) && !$sa_attrib)
1046    $sa_attrib = $attrib;
1047  else if (!is_array($attrib) && is_array($sa_attrib))
1048    $attrib = $sa_attrib;
1049 
1050 
1051  if (!isset($MESSAGE))
1052    return FALSE;
1053
1054  // get associative array of headers object
1055  if (!$headers)
1056    $headers = is_object($MESSAGE['headers']) ? get_object_vars($MESSAGE['headers']) : $MESSAGE['headers'];
1057   
1058  $header_count = 0;
1059 
1060  // allow the following attributes to be added to the <table> tag
1061  $attrib_str = create_attrib_string($attrib, array('style', 'class', 'id', 'cellpadding', 'cellspacing', 'border', 'summary'));
1062  $out = '<table' . $attrib_str . ">\n";
1063
1064  // show these headers
1065  $standard_headers = array('subject', 'from', 'organization', 'to', 'cc', 'bcc', 'reply-to', 'date');
1066 
1067  foreach ($standard_headers as $hkey)
1068    {
1069    if (!$headers[$hkey])
1070      continue;
1071
1072    if ($hkey=='date' && !empty($headers[$hkey]))
1073      $header_value = format_date(strtotime($headers[$hkey]));
1074    else if (in_array($hkey, array('from', 'to', 'cc', 'bcc', 'reply-to')))
1075      $header_value = Q(rcmail_address_string($headers[$hkey], NULL, $attrib['addicon']), 'show');
1076    else
1077      $header_value = Q($IMAP->decode_header($headers[$hkey]));
1078
1079    $out .= "\n<tr>\n";
1080    $out .= '<td class="header-title">'.Q(rcube_label($hkey)).":&nbsp;</td>\n";
1081    $out .= '<td class="'.$hkey.'" width="90%">'.$header_value."</td>\n</tr>";
1082    $header_count++;
1083    }
1084
1085  $out .= "\n</table>\n\n";
1086
1087  return $header_count ? $out : ''; 
1088  }
1089
1090
1091
1092function rcmail_message_body($attrib)
1093  {
1094  global $CONFIG, $OUTPUT, $MESSAGE, $IMAP, $GET_URL, $REMOTE_OBJECTS, $JS_OBJECT_NAME;
1095 
1096  if (!is_array($MESSAGE['parts']) && !$MESSAGE['body'])
1097    return '';
1098   
1099  if (!$attrib['id'])
1100    $attrib['id'] = 'rcmailMsgBody';
1101
1102  $safe_mode = (bool)$_GET['_safe'];
1103  $attrib_str = create_attrib_string($attrib, array('style', 'class', 'id'));
1104  $out = '<div '. $attrib_str . ">\n";
1105 
1106  $header_attrib = array();
1107  foreach ($attrib as $attr => $value)
1108    if (preg_match('/^headertable([a-z]+)$/i', $attr, $regs))
1109      $header_attrib[$regs[1]] = $value;
1110
1111
1112  // this is an ecrypted message
1113  // -> create a plaintext body with the according message
1114  if (!sizeof($MESSAGE['parts']) && $MESSAGE['headers']->ctype=='multipart/encrypted')
1115    {
1116    $p = new stdClass;
1117    $p->type = 'content';
1118    $p->ctype_primary = 'text';
1119    $p->ctype_secondary = 'plain';
1120    $p->body = rcube_label('encryptedmessage');
1121    $MESSAGE['parts'][0] = $p;
1122    }
1123 
1124  if ($MESSAGE['parts'])
1125    {
1126    foreach ($MESSAGE['parts'] as $i => $part)
1127      {
1128      if ($part->type=='headers')
1129        $out .= rcmail_message_headers(sizeof($header_attrib) ? $header_attrib : NULL, $part->headers);
1130      else if ($part->type=='content')
1131        {
1132        if (empty($part->ctype_parameters) || empty($part->ctype_parameters['charset']))
1133          $part->ctype_parameters['charset'] = $MESSAGE['headers']->charset;
1134
1135        // fetch part if not available
1136        if (!isset($part->body))
1137          $part->body = $IMAP->get_message_part($MESSAGE['UID'], $part->mime_id, $part);
1138
1139        $body = rcmail_print_body($part, $safe_mode);
1140        $out .= '<div class="message-part">';
1141       
1142        if ($part->ctype_secondary != 'plain')
1143          $out .= rcmail_mod_html_body($body, $attrib['id']);
1144        else
1145          $out .= $body;
1146
1147        $out .= "</div>\n";
1148        }
1149      }
1150    }
1151  else
1152    $out .= $MESSAGE['body'];
1153
1154
1155  $ctype_primary = strtolower($MESSAGE['structure']->ctype_primary);
1156  $ctype_secondary = strtolower($MESSAGE['structure']->ctype_secondary);
1157 
1158  // list images after mail body
1159  if (get_boolean($attrib['showimages']) && $ctype_primary=='multipart' && $ctype_secondary=='mixed' &&
1160      sizeof($MESSAGE['attachments']) && !strstr($message_body, '<html') && strlen($GET_URL))
1161    {
1162    foreach ($MESSAGE['attachments'] as $attach_prop)
1163      {
1164      if (strpos($attach_prop->mimetype, 'image/')===0)
1165        $out .= sprintf("\n<hr />\n<p align=\"center\"><img src=\"%s&amp;_part=%s\" alt=\"%s\" title=\"%s\" /></p>\n",
1166                        htmlspecialchars($GET_URL), $attach_prop->mime_id,
1167                        $attach_prop->filename,
1168                        $attach_prop->filename);
1169      }
1170    }
1171 
1172  // tell client that there are blocked remote objects
1173  if ($REMOTE_OBJECTS && !$safe_mode)
1174    $OUTPUT->add_script(sprintf("%s.set_env('blockedobjects', true);", $JS_OBJECT_NAME));
1175
1176  $out .= "\n</div>";
1177  return $out;
1178  }
1179
1180
1181
1182// modify a HTML message that it can be displayed inside a HTML page
1183function rcmail_mod_html_body($body, $container_id)
1184  {
1185  // remove any null-byte characters before parsing
1186  $body = preg_replace('/\x00/', '', $body);
1187 
1188  $last_style_pos = 0;
1189  $body_lc = strtolower($body);
1190 
1191  // find STYLE tags
1192  while (($pos = strpos($body_lc, '<style', $last_style_pos)) && ($pos2 = strpos($body_lc, '</style>', $pos)))
1193    {
1194    $pos = strpos($body_lc, '>', $pos)+1;
1195
1196    // replace all css definitions with #container [def]
1197    $styles = rcmail_mod_css_styles(substr($body, $pos, $pos2-$pos), $container_id);
1198
1199    $body = substr($body, 0, $pos) . $styles . substr($body, $pos2);
1200    $body_lc = strtolower($body);
1201    $last_style_pos = $pos2;
1202    }
1203
1204
1205  // remove SCRIPT tags
1206  foreach (array('script', 'applet', 'object', 'embed', 'iframe') as $tag)
1207    {
1208    while (($pos = strpos($body_lc, '<'.$tag)) && ($pos2 = strpos($body_lc, '</'.$tag.'>', $pos)))
1209      {
1210      $pos2 += strlen('</'.$tag.'>');
1211      $body = substr($body, 0, $pos) . substr($body, $pos2, strlen($body)-$pos2);
1212      $body_lc = strtolower($body);
1213      }
1214    }
1215
1216  // replace event handlers on any object
1217  while ($body != $prev_body)
1218    {
1219    $prev_body = $body;
1220    $body = preg_replace('/(<[^!][^>]*\s)(on[^=>]+)=([^>]+>)/im', '$1__removed=$3', $body);
1221    $body = preg_replace('/(<[^!][^>]*\shref=["\']?)(javascript:)([^>]*?>)/im', '$1null:$3', $body);
1222    }
1223
1224  // resolve <base href>
1225  $base_reg = '/(<base.*href=["\']?)([hftps]{3,5}:\/{2}[^"\'\s]+)([^<]*>)/i';
1226  if (preg_match($base_reg, $body, $regs))
1227    {
1228    $base_url = $regs[2];
1229    $body = preg_replace('/(src|background|href)=(["\']?)([\.\/]+[^"\'\s]+)(\2|\s|>)/Uie', "'\\1=\"'.make_absolute_url('\\3', '$base_url').'\"'", $body);
1230    $body = preg_replace('/(url\s*\()(["\']?)([\.\/]+[^"\'\)\s]+)(\2)\)/Uie', "'\\1\''.make_absolute_url('\\3', '$base_url').'\')'", $body);
1231    $body = preg_replace($base_reg, '', $body);
1232    }
1233   
1234  // modify HTML links to open a new window if clicked
1235  $body = preg_replace('/<a\s+([^>]+)>/Uie', "rcmail_alter_html_link('\\1');", $body);
1236
1237  // add comments arround html and other tags
1238  $out = preg_replace(array('/(<\/?html[^>]*>)/i',
1239                            '/(<\/?head[^>]*>)/i',
1240                            '/(<title[^>]*>.*<\/title>)/Ui',
1241                            '/(<\/?meta[^>]*>)/i'),
1242                      '<!--\\1-->',
1243                      $body);
1244
1245  $out = preg_replace(array('/(<body[^>]*>)/i',
1246                            '/(<\/body>)/i'),
1247                      array('<div class="rcmBody">',
1248                            '</div>'),
1249                      $out);
1250
1251  // quote <? of php and xml files that are specified as text/html
1252  $out = preg_replace(array('/<\?/', '/\?>/'), array('&lt;?', '?&gt;'), $out);
1253
1254  return $out;
1255  }
1256
1257
1258// parse link attributes and set correct target
1259function rcmail_alter_html_link($in)
1260  {
1261  $in = preg_replace('/=([^("|\s)]+)(\s|$)/', '="\1"', $in);
1262  $attrib = parse_attrib_string($in);
1263
1264  if (stristr((string)$attrib['href'], 'mailto:'))
1265    $attrib['onclick'] = sprintf("return %s.command('compose','%s',this)",
1266                                 $GLOBALS['JS_OBJECT_NAME'],
1267                                 JQ(substr($attrib['href'], 7)));
1268  else if (!empty($attrib['href']) && $attrib['href']{0}!='#')
1269    $attrib['target'] = '_blank';
1270 
1271  return '<a' . create_attrib_string($attrib, array('href', 'name', 'target', 'onclick', 'id', 'class', 'style', 'title')) . '>';
1272  }
1273
1274
1275// replace all css definitions with #container [def]
1276function rcmail_mod_css_styles($source, $container_id)
1277  {
1278  $a_css_values = array();
1279  $last_pos = 0;
1280 
1281  // cut out all contents between { and }
1282  while (($pos = strpos($source, '{', $last_pos)) && ($pos2 = strpos($source, '}', $pos)))
1283    {
1284    $key = sizeof($a_css_values);
1285    $a_css_values[$key] = substr($source, $pos+1, $pos2-($pos+1));
1286    $source = substr($source, 0, $pos+1) . "<<str_replacement[$key]>>" . substr($source, $pos2, strlen($source)-$pos2);
1287    $last_pos = $pos+2;
1288    }
1289
1290  // remove html commends and add #container to each tag selector.
1291  // also replace body definition because we also stripped off the <body> tag
1292  $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"),
1293                         array('', "\\1#$container_id \\2", "\$a_css_values[\\1]", "$container_id div.rcmBody"),
1294                         $source);
1295
1296  return $styles;
1297  }
1298
1299
1300function rcmail_has_html_part($message_parts)
1301{
1302   if (!is_array($message_parts))
1303      return FALSE;
1304
1305   // check all message parts
1306   foreach ($message_parts as $pid => $part)
1307   {
1308      $mimetype = strtolower($part->ctype_primary.'/'.$part->ctype_secondary);
1309      if ($mimetype=='text/html')
1310      {
1311         return TRUE;
1312      }
1313   }
1314   
1315   return FALSE;
1316}
1317
1318// return first HTML part of a message
1319function rcmail_first_html_part($message_struct)
1320  {
1321  global $IMAP;
1322
1323  if (!is_array($message_struct['parts']))
1324    return FALSE;
1325   
1326  $html_part = NULL;
1327
1328  // check all message parts
1329  foreach ($message_struct['parts'] as $pid => $part)
1330    {
1331    $mimetype = strtolower($part->ctype_primary.'/'.$part->ctype_secondary);
1332    if ($mimetype=='text/html')
1333      {
1334      $html_part = $IMAP->get_message_part($message_struct['UID'], $pid, $part);
1335      }
1336    }
1337
1338  if ($html_part)
1339    {
1340    // remove special chars encoding
1341    //$trans = array_flip(get_html_translation_table(HTML_ENTITIES));
1342    //$html_part = strtr($html_part, $trans);
1343
1344    return $html_part;
1345    }
1346
1347  return FALSE;
1348}
1349
1350
1351// return first text part of a message
1352function rcmail_first_text_part($message_struct)
1353  {
1354  global $IMAP;
1355
1356  if (empty($message_struct['parts']))
1357    return $message_struct['UID'] ? $IMAP->get_body($message_struct['UID']) : false;
1358
1359  // check all message parts
1360  foreach ($message_struct['parts'] as $pid => $part)
1361    {
1362    $mimetype = strtolower($part->ctype_primary.'/'.$part->ctype_secondary);
1363
1364    if ($mimetype=='text/plain')
1365      return $IMAP->get_message_part($message_struct['UID'], $pid, $part);
1366
1367    else if ($mimetype=='text/html')
1368      {
1369      $html_part = $IMAP->get_message_part($message_struct['UID'], $pid, $part);
1370     
1371      // remove special chars encoding
1372      $trans = array_flip(get_html_translation_table(HTML_ENTITIES));
1373      $html_part = strtr($html_part, $trans);
1374
1375      // create instance of html2text class
1376      $txt = new html2text($html_part);
1377      return $txt->get_text();
1378      }
1379    }
1380
1381  return FALSE;
1382  }
1383
1384
1385// decode address string and re-format it as HTML links
1386function rcmail_address_string($input, $max=NULL, $addicon=NULL)
1387  {
1388  global $IMAP, $PRINT_MODE, $CONFIG, $OUTPUT, $JS_OBJECT_NAME, $EMAIL_ADDRESS_PATTERN;
1389 
1390  $a_parts = $IMAP->decode_address_list($input);
1391
1392  if (!sizeof($a_parts))
1393    return $input;
1394
1395  $c = count($a_parts);
1396  $j = 0;
1397  $out = '';
1398
1399  foreach ($a_parts as $part)
1400    {
1401    $j++;
1402    if ($PRINT_MODE)
1403      $out .= sprintf('%s &lt;%s&gt;', Q($part['name']), $part['mailto']);
1404    else if (preg_match($EMAIL_ADDRESS_PATTERN, $part['mailto']))
1405      {
1406      $out .= sprintf('<a href="mailto:%s" onclick="return %s.command(\'compose\',\'%s\',this)" class="rcmContactAddress" title="%s">%s</a>',
1407                      $part['mailto'],
1408                      $JS_OBJECT_NAME,
1409                      $part['mailto'],
1410                      $part['mailto'],
1411                      Q($part['name']));
1412                     
1413      if ($addicon)
1414        $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>',
1415                        $JS_OBJECT_NAME,
1416                        urlencode($part['string']),
1417                        rcube_label('addtoaddressbook'),
1418                        $CONFIG['skin_path'],
1419                        $addicon);
1420      }
1421    else
1422      {
1423      if ($part['name'])
1424        $out .= Q($part['name']);
1425      if ($part['mailto'])
1426        $out .= (strlen($out) ? ' ' : '') . sprintf('&lt;%s&gt;', $part['mailto']);
1427      }
1428     
1429    if ($c>$j)
1430      $out .= ','.($max ? '&nbsp;' : ' ');
1431       
1432    if ($max && $j==$max && $c>$j)
1433      {
1434      $out .= '...';
1435      break;
1436      }       
1437    }
1438   
1439  return $out;
1440  }
1441
1442
1443function rcmail_message_part_controls()
1444  {
1445  global $CONFIG, $IMAP, $MESSAGE;
1446 
1447  if (!is_array($MESSAGE) || !is_array($MESSAGE['parts']) || !($_GET['_uid'] && $_GET['_part']) || !$MESSAGE['parts'][$_GET['_part']])
1448    return '';
1449   
1450  $part = &$MESSAGE['parts'][$_GET['_part']];
1451 
1452  $attrib_str = create_attrib_string($attrib, array('id', 'class', 'style', 'cellspacing', 'cellpadding', 'border', 'summary'));
1453  $out = '<table '. $attrib_str . ">\n";
1454 
1455  $filename = $part->d_parameters['filename'] ? $part->d_parameters['filename'] : $part->ctype_parameters['name'];
1456  $filesize = $part->size;
1457 
1458  if ($filename)
1459    {
1460    $out .= sprintf('<tr><td class="title">%s</td><td>%s</td><td>[<a href="./?%s">%s</a>]</tr>'."\n",
1461                    Q(rcube_label('filename')),
1462                    Q(rcube_imap::decode_mime_string($filename)),
1463                    str_replace('_frame=', '_download=', $_SERVER['QUERY_STRING']),
1464                    Q(rcube_label('download')));
1465    }
1466   
1467  if ($filesize)
1468    $out .= sprintf('<tr><td class="title">%s</td><td>%s</td></tr>'."\n",
1469                    Q(rcube_label('filesize')),
1470                    show_bytes($filesize));
1471 
1472  $out .= "\n</table>";
1473 
1474  return $out;
1475  }
1476
1477
1478
1479function rcmail_message_part_frame($attrib)
1480  {
1481  global $MESSAGE;
1482 
1483  $part = $MESSAGE['parts'][$_GET['_part']];
1484  $ctype_primary = strtolower($part->ctype_primary);
1485
1486  $attrib['src'] = './?'.str_replace('_frame=', ($ctype_primary=='text' ? '_show=' : '_preload='), $_SERVER['QUERY_STRING']);
1487
1488  $attrib_str = create_attrib_string($attrib, array('id', 'class', 'style', 'src', 'width', 'height'));
1489  $out = '<iframe '. $attrib_str . "></iframe>";
1490   
1491  return $out;
1492  }
1493
1494
1495// clear message composing settings
1496function rcmail_compose_cleanup()
1497  {
1498  if (!isset($_SESSION['compose']))
1499    return;
1500
1501  // remove attachment files from temp dir
1502  if (is_array($_SESSION['compose']['attachments']))
1503    foreach ($_SESSION['compose']['attachments'] as $attachment)
1504      @unlink($attachment['path']);
1505 
1506  unset($_SESSION['compose']);
1507  }
1508 
1509 
1510?>
Note: See TracBrowser for help on using the repository browser.