source: github/program/steps/mail/func.inc @ cfe4a6b

HEADcourier-fixdev-browser-capabilitiespdorelease-0.6release-0.7release-0.8
Last change on this file since cfe4a6b was cfe4a6b, checked in by thomascube <thomas@…>, 5 years ago

Fix structure parsing and html output for multipart messages

  • Property mode set to 100644
File size: 35.4 KB
Line 
1<?php
2
3/*
4 +-----------------------------------------------------------------------+
5 | program/steps/mail/func.inc                                           |
6 |                                                                       |
7 | This file is part of the RoundCube Webmail client                     |
8 | Copyright (C) 2005-2008, 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/enriched.inc');
23require_once('include/rcube_smtp.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// set imap properties and session vars
32if ($mbox = get_input_value('_mbox', RCUBE_INPUT_GPC))
33  $IMAP->set_mailbox(($_SESSION['mbox'] = $mbox));
34
35if (!empty($_GET['_page']))
36  $IMAP->set_page(($_SESSION['page'] = intval($_GET['_page'])));
37
38// set mailbox to INBOX if not set
39if (empty($_SESSION['mbox']))
40  $_SESSION['mbox'] = $IMAP->get_mailbox_name();
41
42// set default sort col/order to session
43if (!isset($_SESSION['sort_col']))
44  $_SESSION['sort_col'] = $CONFIG['message_sort_col'];
45if (!isset($_SESSION['sort_order']))
46  $_SESSION['sort_order'] = $CONFIG['message_sort_order'];
47
48// set message set for search result
49if (!empty($_REQUEST['_search']) && isset($_SESSION['search'][$_REQUEST['_search']]))
50  {
51  $IMAP->set_search_set($_SESSION['search'][$_REQUEST['_search']]);
52  $OUTPUT->set_env('search_request', $_REQUEST['_search']);
53  $OUTPUT->set_env('search_text', $_SESSION['last_text_search']);
54  }
55
56
57// set current mailbox in client environment
58$OUTPUT->set_env('mailbox', $IMAP->get_mailbox_name());
59$OUTPUT->set_env('quota', $IMAP->get_capability('quota'));
60
61if ($CONFIG['trash_mbox'])
62  $OUTPUT->set_env('trash_mailbox', $CONFIG['trash_mbox']);
63if ($CONFIG['drafts_mbox'])
64  $OUTPUT->set_env('drafts_mailbox', $CONFIG['drafts_mbox']);
65if ($CONFIG['junk_mbox'])
66  $OUTPUT->set_env('junk_mailbox', $CONFIG['junk_mbox']);
67
68if (!$OUTPUT->ajax_call)
69  rcube_add_label('checkingmail', 'deletemessage', 'movemessagetotrash', 'movingmessage');
70
71// set page title
72if (empty($RCMAIL->action) || $RCMAIL->action == 'list')
73  $OUTPUT->set_pagetitle(rcmail_localize_foldername($IMAP->get_mailbox_name()));
74
75
76
77/**
78 * return the message list as HTML table
79 */
80function rcmail_message_list($attrib)
81  {
82  global $IMAP, $CONFIG, $COMM_PATH, $OUTPUT;
83
84  $skin_path = $CONFIG['skin_path'];
85  $image_tag = '<img src="%s%s" alt="%s" border="0" />';
86
87  // check to see if we have some settings for sorting
88  $sort_col   = $_SESSION['sort_col'];
89  $sort_order = $_SESSION['sort_order'];
90 
91  // add some labels to client
92  rcube_add_label('from', 'to');
93
94  // get message headers
95  $a_headers = $IMAP->list_headers('', '', $sort_col, $sort_order);
96
97  // add id to message list table if not specified
98  if (!strlen($attrib['id']))
99    $attrib['id'] = 'rcubemessagelist';
100
101  // allow the following attributes to be added to the <table> tag
102  $attrib_str = create_attrib_string($attrib, array('style', 'class', 'id', 'cellpadding', 'cellspacing', 'border', 'summary'));
103
104  $out = '<table' . $attrib_str . ">\n";
105
106
107  // define list of cols to be displayed
108  $a_show_cols = is_array($CONFIG['list_cols']) ? $CONFIG['list_cols'] : array('subject');
109  $a_sort_cols = array('subject', 'date', 'from', 'to', 'size');
110
111  $mbox = $IMAP->get_mailbox_name();
112 
113  // show 'to' instead of from in sent messages
114  if (($mbox==$CONFIG['sent_mbox'] || $mbox==$CONFIG['drafts_mbox']) && ($f = array_search('from', $a_show_cols))
115      && !array_search('to', $a_show_cols))
116    $a_show_cols[$f] = 'to';
117 
118  // add col definition
119  $out .= '<colgroup>';
120  $out .= '<col class="icon" />';
121
122  foreach ($a_show_cols as $col)
123    $out .= sprintf('<col class="%s" />', $col);
124
125  $out .= '<col class="icon" />';
126  $out .= "</colgroup>\n";
127
128  // add table title
129  $out .= "<thead><tr>\n<td class=\"icon\">&nbsp;</td>\n";
130
131  $javascript = '';
132  foreach ($a_show_cols as $col)
133    {
134    // get column name
135    $col_name = Q(rcube_label($col));
136
137    // make sort links
138    $sort = '';
139    if (in_array($col, $a_sort_cols))
140      {
141      // have buttons configured
142      if (!empty($attrib['sortdescbutton']) || !empty($attrib['sortascbutton']))
143        {
144        $sort = '&nbsp;&nbsp;';
145
146        // asc link
147        if (!empty($attrib['sortascbutton']))
148          {
149          $sort .= $OUTPUT->button(array(
150            'command' => 'sort',
151            'prop' => $col.'_ASC',
152            'image' => $attrib['sortascbutton'],
153            'align' => 'absmiddle',
154            'title' => 'sortasc'));
155          }       
156       
157        // desc link
158        if (!empty($attrib['sortdescbutton']))
159          {
160          $sort .= $OUTPUT->button(array(
161            'command' => 'sort',
162            'prop' => $col.'_DESC',
163            'image' => $attrib['sortdescbutton'],
164            'align' => 'absmiddle',
165            'title' => 'sortdesc'));
166          }
167        }
168      // just add a link tag to the header
169      else
170        {
171        $col_name = sprintf(
172          '<a href="./#sort" onclick="return %s.command(\'sort\',\'%s\',this)" title="%s">%s</a>',
173          JS_OBJECT_NAME,
174          $col,
175          rcube_label('sortby'),
176          $col_name);
177        }
178      }
179     
180    $sort_class = $col==$sort_col ? " sorted$sort_order" : '';
181
182    // put it all together
183    $out .= '<td class="'.$col.$sort_class.'" id="rcmHead'.$col.'">' . "$col_name$sort</td>\n";   
184    }
185
186  $out .= '<td class="icon">'.($attrib['attachmenticon'] ? sprintf($image_tag, $skin_path, $attrib['attachmenticon'], '') : '')."</td>\n";
187  $out .= "</tr></thead>\n<tbody>\n";
188
189  // no messages in this mailbox
190  if (!sizeof($a_headers))
191    $OUTPUT->show_message('nomessagesfound', 'notice');
192
193
194  $a_js_message_arr = array();
195
196  // create row for each message
197  foreach ($a_headers as $i => $header)  //while (list($i, $header) = each($a_headers))
198    {
199    $message_icon = $attach_icon = '';
200    $js_row_arr = array();
201    $zebra_class = $i%2 ? 'even' : 'odd';
202
203    // set messag attributes to javascript array
204    if ($header->deleted)
205      $js_row_arr['deleted'] = true;
206    if (!$header->seen)
207      $js_row_arr['unread'] = true;
208    if ($header->answered)
209      $js_row_arr['replied'] = true;
210    // set message icon 
211    if ($attrib['deletedicon'] && $header->deleted)
212      $message_icon = $attrib['deletedicon'];
213    else if ($attrib['unreadicon'] && !$header->seen)
214      $message_icon = $attrib['unreadicon'];
215    else if ($attrib['repliedicon'] && $header->answered)
216      $message_icon = $attrib['repliedicon'];
217    else if ($attrib['messageicon'])
218      $message_icon = $attrib['messageicon'];
219   
220    // set attachment icon
221    if ($attrib['attachmenticon'] && preg_match("/multipart\/[mr]/i", $header->ctype))
222      $attach_icon = $attrib['attachmenticon'];
223       
224    $out .= sprintf('<tr id="rcmrow%d" class="message%s%s %s">'."\n",
225                    $header->uid,
226                    $header->seen ? '' : ' unread',
227                    $header->deleted ? ' deleted' : '',
228                    $zebra_class);   
229   
230    $out .= sprintf("<td class=\"icon\">%s</td>\n", $message_icon ? sprintf($image_tag, $skin_path, $message_icon, '') : '');
231
232    if (!empty($header->charset))
233      $IMAP->set_charset($header->charset);
234 
235    // format each col
236    foreach ($a_show_cols as $col)
237      {
238      if ($col=='from' || $col=='to')
239        $cont = Q(rcmail_address_string($header->$col, 3, $attrib['addicon']), 'show');
240      else if ($col=='subject')
241        {
242        $action = $mbox==$CONFIG['drafts_mbox'] ? 'compose' : 'show';
243        $uid_param = $mbox==$CONFIG['drafts_mbox'] ? '_draft_uid' : '_uid';
244        $cont = Q($IMAP->decode_header($header->$col));
245        if (empty($cont)) $cont = Q(rcube_label('nosubject'));
246        $cont = sprintf('<a href="%s" onclick="return rcube_event.cancel(event)">%s</a>', Q(rcmail_url($action, array($uid_param=>$header->uid, '_mbox'=>$mbox))), $cont);
247        }
248      else if ($col=='size')
249        $cont = show_bytes($header->$col);
250      else if ($col=='date')
251        $cont = format_date($header->date);
252      else
253        $cont = Q($header->$col);
254       
255      $out .= '<td class="'.$col.'">' . $cont . "</td>\n";
256      }
257
258    $out .= sprintf("<td class=\"icon\">%s</td>\n", $attach_icon ? sprintf($image_tag, $skin_path, $attach_icon, '') : '');
259    $out .= "</tr>\n";
260   
261    if (sizeof($js_row_arr))
262      $a_js_message_arr[$header->uid] = $js_row_arr;
263    }
264 
265  // complete message table
266  $out .= "</tbody></table>\n";
267 
268 
269  $message_count = $IMAP->messagecount();
270 
271  // set client env
272  $OUTPUT->add_gui_object('mailcontframe', 'mailcontframe');
273  $OUTPUT->add_gui_object('messagelist', $attrib['id']);
274  $OUTPUT->set_env('messagecount', $message_count);
275  $OUTPUT->set_env('current_page', $IMAP->list_page);
276  $OUTPUT->set_env('pagecount', ceil($message_count/$IMAP->page_size));
277  $OUTPUT->set_env('sort_col', $sort_col);
278  $OUTPUT->set_env('sort_order', $sort_order);
279 
280  if ($attrib['messageicon'])
281    $OUTPUT->set_env('messageicon', $skin_path . $attrib['messageicon']);
282  if ($attrib['deletedicon'])
283    $OUTPUT->set_env('deletedicon', $skin_path . $attrib['deletedicon']);
284  if ($attrib['unreadicon'])
285    $OUTPUT->set_env('unreadicon', $skin_path . $attrib['unreadicon']);
286  if ($attrib['repliedicon'])
287    $OUTPUT->set_env('repliedicon', $skin_path . $attrib['repliedicon']);
288  if ($attrib['attachmenticon'])
289    $OUTPUT->set_env('attachmenticon', $skin_path . $attrib['attachmenticon']);
290 
291  $OUTPUT->set_env('messages', $a_js_message_arr);
292  $OUTPUT->set_env('coltypes', $a_show_cols);
293 
294  $OUTPUT->include_script('list.js');
295 
296  return $out;
297  }
298
299
300/**
301 * return javascript commands to add rows to the message list
302 */
303function rcmail_js_message_list($a_headers, $insert_top=FALSE)
304  {
305  global $CONFIG, $IMAP, $OUTPUT;
306
307  $a_show_cols = is_array($CONFIG['list_cols']) ? $CONFIG['list_cols'] : array('subject');
308  $mbox = $IMAP->get_mailbox_name();
309
310  // show 'to' instead of from in sent messages
311  if (($mbox == $CONFIG['sent_mbox'] || $mbox == $CONFIG['drafts_mbox'])
312      && (($f = array_search('from', $a_show_cols)) !== false) && array_search('to', $a_show_cols) === false)
313    $a_show_cols[$f] = 'to';
314
315  $OUTPUT->command('set_message_coltypes', $a_show_cols);
316
317  // loop through message headers
318  foreach ($a_headers as $n => $header)
319    {
320    $a_msg_cols = array();
321    $a_msg_flags = array();
322   
323    if (empty($header))
324      continue;
325
326    if (!empty($header->charset))
327      $IMAP->set_charset($header->charset);
328
329    // format each col; similar as in rcmail_message_list()
330    foreach ($a_show_cols as $col)
331      {
332      if ($col=='from' || $col=='to')
333        $cont = Q(rcmail_address_string($header->$col, 3), 'show');
334      else if ($col=='subject')
335        {
336        $action = $mbox==$CONFIG['drafts_mbox'] ? 'compose' : 'show';
337        $uid_param = $mbox==$CONFIG['drafts_mbox'] ? '_draft_uid' : '_uid';
338        $cont = Q($IMAP->decode_header($header->$col));
339        if (!$cont) $cont = Q(rcube_label('nosubject'));
340        $cont = sprintf('<a href="%s" onclick="return rcube_event.cancel(event)">%s</a>', Q(rcmail_url($action, array($uid_param=>$header->uid, '_mbox'=>$mbox))), $cont);
341        }
342      else if ($col=='size')
343        $cont = show_bytes($header->$col);
344      else if ($col=='date')
345        $cont = format_date($header->date);
346      else
347        $cont = Q($header->$col);
348         
349      $a_msg_cols[$col] = $cont;
350      }
351
352    $a_msg_flags['deleted'] = $header->deleted ? 1 : 0;
353    $a_msg_flags['unread'] = $header->seen ? 0 : 1;
354    $a_msg_flags['replied'] = $header->answered ? 1 : 0;
355    $OUTPUT->command('add_message_row',
356      $header->uid,
357      $a_msg_cols,
358      $a_msg_flags,
359      preg_match("/multipart\/m/i", $header->ctype),
360      $insert_top);
361    }
362  }
363
364
365/**
366 * return an HTML iframe for loading mail content
367 */
368function rcmail_messagecontent_frame($attrib)
369  {
370  global $OUTPUT;
371 
372  if (empty($attrib['id']))
373    $attrib['id'] = 'rcmailcontentwindow';
374
375  // allow the following attributes to be added to the <iframe> tag
376  $attrib_str = create_attrib_string($attrib, array('id', 'class', 'style', 'src', 'width', 'height', 'frameborder'));
377  $framename = $attrib['id'];
378
379  $out = sprintf('<iframe name="%s"%s></iframe>'."\n",
380         $framename,
381         $attrib_str);
382
383  $OUTPUT->set_env('contentframe', $framename);
384  $OUTPUT->set_env('blankpage', $attrib['src'] ? $OUTPUT->abs_url($attrib['src']) : 'program/blank.gif');
385
386  return $out;
387  }
388
389
390/**
391 *
392 */
393function rcmail_messagecount_display($attrib)
394  {
395  global $IMAP, $OUTPUT;
396 
397  if (!$attrib['id'])
398    $attrib['id'] = 'rcmcountdisplay';
399
400  $OUTPUT->add_gui_object('countdisplay', $attrib['id']);
401
402  // allow the following attributes to be added to the <span> tag
403  $attrib_str = create_attrib_string($attrib, array('style', 'class', 'id'));
404
405 
406  $out = '<span' . $attrib_str . '>';
407  $out .= rcmail_get_messagecount_text();
408  $out .= '</span>';
409  return $out;
410  }
411
412
413/**
414 *
415 */
416function rcmail_quota_display($attrib)
417  {
418  global $OUTPUT, $COMM_PATH;
419
420  if (!$attrib['id'])
421    $attrib['id'] = 'rcmquotadisplay';
422
423  if(isset($attrib['display']))
424    $_SESSION['quota_display'] = $attrib['display'];
425
426  $OUTPUT->add_gui_object('quotadisplay', $attrib['id']);
427
428  // allow the following attributes to be added to the <span> tag
429  $attrib_str = create_attrib_string($attrib, array('style', 'class', 'id', 'display'));
430
431  $out = '<span' . $attrib_str . '>';
432  $out .= rcmail_quota_content();
433  $out .= '</span>';
434  return $out;
435  }
436
437
438/**
439 *
440 */
441function rcmail_quota_content($quota=NULL)
442  {
443  global $IMAP, $COMM_PATH;
444
445  $display = isset($_SESSION['quota_display']) ? $_SESSION['quota_display'] : '';
446
447  if (is_array($quota) && !empty($quota['used']) && !empty($quota['total']))
448    {
449      if (!isset($quota['percent']))
450        $quota['percent'] = $quota['used'] / $quota['total'];
451    }
452  elseif (!$IMAP->get_capability('QUOTA'))
453    return rcube_label('unknown');
454  else
455    $quota = $IMAP->get_quota();
456
457  if ($quota)
458    {
459    $quota_text = sprintf('%s / %s (%.0f%%)',
460                          show_bytes($quota['used'] * 1024),
461                          show_bytes($quota['total'] * 1024),
462                          $quota['percent']);
463
464    // show quota as image (by Brett Patterson)
465    if ($display == 'image' && function_exists('imagegif'))
466      {
467      $attrib = array('width' => 100, 'height' => 14);
468      $quota_text = sprintf('<img src="./bin/quotaimg.php?u=%s&amp;q=%d&amp;w=%d&amp;h=%d" width="%d" height="%d" alt="%s" title="%s / %s" />',
469                            $quota['used'], $quota['total'],
470                            $attrib['width'], $attrib['height'],
471                            $attrib['width'], $attrib['height'],
472                            $quota_text,
473                            show_bytes($quota["used"] * 1024),
474                            show_bytes($quota["total"] * 1024));
475      }
476    }
477  else
478    $quota_text = rcube_label('unlimited');
479
480  return $quota_text;
481  }
482
483
484/**
485 *
486 */
487function rcmail_get_messagecount_text($count=NULL, $page=NULL)
488  {
489  global $IMAP, $MESSAGE;
490 
491  if (isset($MESSAGE->index))
492    {
493    return rcube_label(array('name' => 'messagenrof',
494                             'vars' => array('nr'  => $MESSAGE->index+1,
495                                             'count' => $count!==NULL ? $count : $IMAP->messagecount())));
496    }
497
498  if ($page===NULL)
499    $page = $IMAP->list_page;
500   
501  $start_msg = ($page-1) * $IMAP->page_size + 1;
502  $max = $count!==NULL ? $count : $IMAP->messagecount();
503
504  if ($max==0)
505    $out = rcube_label('mailboxempty');
506  else
507    $out = rcube_label(array('name' => 'messagesfromto',
508                              'vars' => array('from'  => $start_msg,
509                                              'to'    => min($max, $start_msg + $IMAP->page_size - 1),
510                                              'count' => $max)));
511
512  return Q($out);
513  }
514
515
516/**
517 * Convert the given message part to proper HTML
518 * which can be displayed the message view
519 *
520 * @param object rcube_message_part Message part
521 * @param bool  True if external objects (ie. images ) are allowed
522 * @param bool  True if part should be converted to plaintext
523 * @return string Formatted HTML string
524 */
525function rcmail_print_body($part, $safe=false, $plain=false)
526{
527  global $REMOTE_OBJECTS;
528 
529  // convert html to text/plain
530  if ($part->ctype_secondary == 'html' && $plain) {
531    $txt = new html2text($part->body, false, true);
532    $body = $txt->get_text();
533    $part->ctype_secondary = 'plain';
534  }
535  // text/html
536  else if ($part->ctype_secondary == 'html') {
537    // clean HTML with washhtml by Frederic Motte
538    $body = washtml::wash($part->body, array(
539      'show_washed' => false,
540      'allow_remote' => $safe,
541      'blocked_src' => "./program/blocked.gif",
542      'charset' => 'UTF-8',
543      'cid_map' => $part->replaces,
544      ), $full_inline);
545
546    $REMOTE_OBJECTS = !$full_inline;
547
548    return $body;
549  }
550  // text/enriched
551  else if ($part->ctype_secondary=='enriched') {
552    $part->ctype_secondary = 'html';
553    return Q(enriched_to_html($body), 'show');
554  }
555  else
556    $body = $part->body;
557
558
559  /**** assert plaintext ****/
560
561  // make links and email-addresses clickable
562  $convert_patterns = $convert_replaces = $replace_strings = array();
563 
564  $url_chars = 'a-z0-9_\-\+\*\$\/&%=@#:;';
565  $url_chars_within = '\?\.~,!';
566
567  $convert_patterns[] = "/([\w]+):\/\/([a-z0-9\-\.]+[a-z]{2,4}([$url_chars$url_chars_within]*[$url_chars])?)/ie";
568  $convert_replaces[] = "rcmail_str_replacement('<a href=\"\\1://\\2\" target=\"_blank\">\\1://\\2</a>', \$replace_strings)";
569
570  $convert_patterns[] = "/([^\/:]|\s)(www\.)([a-z0-9\-]{2,}[a-z]{2,4}([$url_chars$url_chars_within]*[$url_chars])?)/ie";
571  $convert_replaces[] = "rcmail_str_replacement('\\1<a href=\"http://\\2\\3\" target=\"_blank\">\\2\\3</a>', \$replace_strings)";
572 
573  $convert_patterns[] = '/([a-z0-9][a-z0-9\-\.\+\_]*@[a-z0-9]([a-z0-9\-][.]?)*[a-z0-9]\\.[a-z]{2,5})/ie';
574  $convert_replaces[] = "rcmail_str_replacement('<a href=\"mailto:\\1\" onclick=\"return ".JS_OBJECT_NAME.".command(\'compose\',\'\\1\',this)\">\\1</a>', \$replace_strings)";
575 
576//    if ($part->ctype_parameters['format'] != 'flowed')
577//      $body = wordwrap(trim($body), 80);
578
579  // search for patterns like links and e-mail addresses
580  $body = preg_replace($convert_patterns, $convert_replaces, $body);
581
582  // split body into single lines
583  $a_lines = preg_split('/\r?\n/', $body);
584  $quote_level = 0;
585
586  // colorize quoted parts
587  for ($n=0; $n < sizeof($a_lines); $n++) {
588    $line = $a_lines[$n];
589    $quotation = '';
590    $q = 0;
591   
592    if (preg_match('/^(>+\s*)+/', $line, $regs)) {
593      $q    = strlen(preg_replace('/\s/', '', $regs[0]));
594      $line = substr($line, strlen($regs[0]));
595
596      if ($q > $quote_level)
597        $quotation = str_repeat('<blockquote>', $q - $quote_level);
598      else if ($q < $quote_level)
599        $quotation = str_repeat("</blockquote>", $quote_level - $q);
600    }
601    else if ($quote_level > 0)
602      $quotation = str_repeat("</blockquote>", $quote_level);
603
604    $quote_level = $q;
605    $a_lines[$n] = $quotation . Q($line, 'replace', false);  // htmlquote plaintext
606  }
607
608  // insert the links for urls and mailtos
609  $body = preg_replace("/##string_replacement\{([0-9]+)\}##/e", "\$replace_strings[\\1]", join("\n", $a_lines));
610 
611  return "<div class=\"pre\">".$body."\n</div>";
612  }
613
614
615
616/**
617 * add a string to the replacement array and return a replacement string
618 */
619function rcmail_str_replacement($str, &$rep)
620  {
621  static $count = 0;
622  $rep[$count] = stripslashes($str);
623  return "##string_replacement{".($count++)."}##";
624  }
625
626
627
628/**
629 * return table with message headers
630 */
631function rcmail_message_headers($attrib, $headers=NULL)
632  {
633  global $IMAP, $OUTPUT, $MESSAGE;
634  static $sa_attrib;
635 
636  // keep header table attrib
637  if (is_array($attrib) && !$sa_attrib)
638    $sa_attrib = $attrib;
639  else if (!is_array($attrib) && is_array($sa_attrib))
640    $attrib = $sa_attrib;
641 
642 
643  if (!isset($MESSAGE))
644    return FALSE;
645
646  // get associative array of headers object
647  if (!$headers)
648    $headers = is_object($MESSAGE->headers) ? get_object_vars($MESSAGE->headers) : $MESSAGE->headers;
649   
650  // add empty subject if none exsists
651  if (empty($headers['subject']))
652    $headers['subject'] = rcube_label('nosubject');
653 
654  $header_count = 0;
655 
656  // allow the following attributes to be added to the <table> tag
657  $attrib_str = create_attrib_string($attrib, array('style', 'class', 'id', 'cellpadding', 'cellspacing', 'border', 'summary'));
658  $out = '<table' . $attrib_str . ">\n";
659
660  // show these headers
661  $standard_headers = array('subject', 'from', 'organization', 'to', 'cc', 'bcc', 'reply-to', 'date');
662 
663  foreach ($standard_headers as $hkey)
664    {
665    if (!$headers[$hkey])
666      continue;
667
668    if ($hkey=='date' && !empty($headers[$hkey]))
669      $header_value = format_date($headers[$hkey]);
670    else if (in_array($hkey, array('from', 'to', 'cc', 'bcc', 'reply-to')))
671      $header_value = Q(rcmail_address_string($headers[$hkey], NULL, $attrib['addicon']), 'show');
672    else
673      $header_value = Q($IMAP->decode_header($headers[$hkey]));
674
675    $out .= "\n<tr>\n";
676    $out .= '<td class="header-title">'.Q(rcube_label($hkey)).":&nbsp;</td>\n";
677    $out .= '<td class="'.$hkey.'" width="90%">'.$header_value."</td>\n</tr>";
678    $header_count++;
679    }
680
681  $out .= "\n</table>\n\n";
682
683  return $header_count ? $out : ''; 
684  }
685
686
687/**
688 * Handler for the 'messagebody' GUI object
689 *
690 * @param array Named parameters
691 * @return string HTML content showing the message body
692 */
693function rcmail_message_body($attrib)
694  {
695  global $CONFIG, $OUTPUT, $MESSAGE, $IMAP, $REMOTE_OBJECTS;
696 
697  if (!is_array($MESSAGE->parts) && empty($MESSAGE->body))
698    return '';
699   
700  if (!$attrib['id'])
701    $attrib['id'] = 'rcmailMsgBody';
702
703  $safe_mode = $MESSAGE->is_safe || intval($_GET['_safe']);
704  $out = '';
705 
706  $header_attrib = array();
707  foreach ($attrib as $attr => $value)
708    if (preg_match('/^headertable([a-z]+)$/i', $attr, $regs))
709      $header_attrib[$regs[1]] = $value;
710
711  if (!empty($MESSAGE->parts))
712    {
713    foreach ($MESSAGE->parts as $i => $part)
714      {
715      if ($part->type == 'headers')
716        $out .= rcmail_message_headers(sizeof($header_attrib) ? $header_attrib : NULL, $part->headers);
717      else if ($part->type == 'content')
718        {
719        if (empty($part->ctype_parameters) || empty($part->ctype_parameters['charset']))
720          $part->ctype_parameters['charset'] = $MESSAGE->headers->charset;
721
722        // fetch part if not available
723        if (!isset($part->body))
724          $part->body = $MESSAGE->get_part_content($part->mime_id);
725
726        $body = rcmail_print_body($part, $safe_mode, !$CONFIG['prefer_html']);
727       
728        if ($part->ctype_secondary == 'html')
729          $out .= html::div('message-htmlpart', rcmail_html4inline($body, $attrib['id']));
730        else
731          $out .= html::div('message-part', $body);
732        }
733      }
734    }
735  else
736    $out .= html::div('message-part', html::div('pre', Q($MESSAGE->body)));
737
738
739  $ctype_primary = strtolower($MESSAGE->structure->ctype_primary);
740  $ctype_secondary = strtolower($MESSAGE->structure->ctype_secondary);
741 
742  // list images after mail body
743  if (get_boolean($attrib['showimages']) && $ctype_primary == 'multipart' &&
744      !empty($MESSAGE->attachments) && !strstr($message_body, '<html')) {
745    foreach ($MESSAGE->attachments as $attach_prop) {
746      if (strpos($attach_prop->mimetype, 'image/') === 0) {
747        $out .= html::tag('hr') . html::p(array('align' => "center"),
748          html::img(array(
749            'src' => $MESSAGE->get_part_url($attach_prop->mime_id),
750            'title' => $attach_prop->filename,
751            'alt' => $attach_prop->filename,
752          )));
753        }
754    }
755  }
756 
757  // tell client that there are blocked remote objects
758  if ($REMOTE_OBJECTS && !$safe_mode)
759    $OUTPUT->set_env('blockedobjects', true);
760
761  return html::div($attrib, $out);
762  }
763
764
765
766/**
767 * modify a HTML message that it can be displayed inside a HTML page
768 */
769function rcmail_html4inline($body, $container_id)
770  {
771  $base_url = "";
772  $last_style_pos = 0;
773  $body_lc = strtolower($body);
774 
775  // check for <base href>
776  if (preg_match(($base_reg = '/(<base.*href=["\']?)([hftps]{3,5}:\/{2}[^"\'\s]+)([^<]*>)/i'), $body, $base_regs))
777    $base_url = $base_regs[2];
778 
779  // find STYLE tags
780  while (($pos = strpos($body_lc, '<style', $last_style_pos)) && ($pos2 = strpos($body_lc, '</style>', $pos)))
781    {
782    $pos = strpos($body_lc, '>', $pos)+1;
783
784    // replace all css definitions with #container [def]
785    $styles = rcmail_mod_css_styles(substr($body, $pos, $pos2-$pos), $container_id, $base_url);
786
787    $body = substr($body, 0, $pos) . $styles . substr($body, $pos2);
788    $body_lc = strtolower($body);
789    $last_style_pos = $pos2;
790    }
791
792  // resolve <base href>
793  if ($base_url)
794    {
795    $body = preg_replace('/(src|background|href)=(["\']?)([\.\/]+[^"\'\s]+)(\2|\s|>)/Uie', "'\\1=\"'.make_absolute_url('\\3', '$base_url').'\"'", $body);
796    $body = preg_replace('/(url\s*\()(["\']?)([\.\/]+[^"\'\)\s]+)(\2)\)/Uie', "'\\1\''.make_absolute_url('\\3', '$base_url').'\')'", $body);
797    $body = preg_replace($base_reg, '', $body);
798    }
799   
800  // modify HTML links to open a new window if clicked
801  $body = preg_replace('/<(a|link)\s+([^>]+)>/Uie', "rcmail_alter_html_link('\\1','\\2', '$container_id');", $body);
802
803  // add comments arround html and other tags
804  $out = preg_replace(array(
805      '/(<!DOCTYPE[^>]*>)/i',
806      '/(<\?xml[^>]*>)/i',
807      '/(<\/?html[^>]*>)/i',
808      '/(<\/?head[^>]*>)/i',
809      '/(<title[^>]*>.*<\/title>)/Ui',
810      '/(<\/?meta[^>]*>)/i'),
811    '<!--\\1-->',
812    $body);
813
814  $out = preg_replace(
815    array('/<body([^>]*)>/i', '/<\/body>/i'),
816    array('<div class="rcmBody"\\1>', '</div>'),
817    $out);
818
819  // quote <? of php and xml files that are specified as text/html
820  $out = preg_replace(array('/<\?/', '/\?>/'), array('&lt;?', '?&gt;'), $out);
821
822  return $out;
823  }
824
825
826/**
827 * parse link attributes and set correct target
828 */
829function rcmail_alter_html_link($tag, $attrs, $container_id)
830  {
831  $attrib = parse_attrib_string($attrs);
832
833  if ($tag == 'link' && preg_match('/^https?:\/\//i', $attrib['href']))
834    $attrib['href'] = "./bin/modcss.php?u=" . urlencode($attrib['href']) . "&amp;c=" . urlencode($container_id);
835
836  else if (stristr((string)$attrib['href'], 'mailto:'))
837    $attrib['onclick'] = sprintf(
838      "return %s.command('compose','%s',this)",
839      JS_OBJECT_NAME,
840      JQ(substr($attrib['href'], 7)));
841
842  else if (!empty($attrib['href']) && $attrib['href']{0}!='#')
843    $attrib['target'] = '_blank';
844
845  return "<$tag" . create_attrib_string($attrib, array('href','name','target','onclick','id','class','style','title','rel','type','media')) . ' />';
846  }
847
848
849/**
850 * decode address string and re-format it as HTML links
851 */
852function rcmail_address_string($input, $max=NULL, $addicon=NULL)
853  {
854  global $IMAP, $PRINT_MODE, $CONFIG, $OUTPUT, $EMAIL_ADDRESS_PATTERN;
855
856  $a_parts = $IMAP->decode_address_list($input);
857
858  if (!sizeof($a_parts))
859    return $input;
860
861  $c = count($a_parts);
862  $j = 0;
863  $out = '';
864
865  foreach ($a_parts as $part)
866    {
867    $j++;
868    if ($PRINT_MODE)
869      $out .= sprintf('%s &lt;%s&gt;', Q($part['name']), $part['mailto']);
870    else if (preg_match($EMAIL_ADDRESS_PATTERN, $part['mailto']))
871      {
872      $out .= sprintf('<a href="mailto:%s" onclick="return %s.command(\'compose\',\'%s\',this)" class="rcmContactAddress" title="%s">%s</a>',
873                      Q($part['mailto']),
874                      JS_OBJECT_NAME,
875                      JQ($part['mailto']),
876                      Q($part['mailto']),
877                      Q($part['name']));
878                     
879      if ($addicon)
880        $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>',
881                        JS_OBJECT_NAME,
882                        urlencode($part['string']),
883                        rcube_label('addtoaddressbook'),
884                        $CONFIG['skin_path'],
885                        $addicon);
886      }
887    else
888      {
889      if ($part['name'])
890        $out .= Q($part['name']);
891      if ($part['mailto'])
892        $out .= (strlen($out) ? ' ' : '') . sprintf('&lt;%s&gt;', Q($part['mailto']));
893      }
894     
895    if ($c>$j)
896      $out .= ','.($max ? '&nbsp;' : ' ');
897       
898    if ($max && $j==$max && $c>$j)
899      {
900      $out .= '...';
901      break;
902      }       
903    }
904   
905  return $out;
906  }
907
908
909function rcmail_message_part_controls()
910  {
911  global $MESSAGE;
912 
913  $part = asciiwords(get_input_value('_part', RCUBE_INPUT_GPC));
914  if (!is_object($MESSAGE) || !is_array($MESSAGE->parts) || !($_GET['_uid'] && $_GET['_part']) || !$MESSAGE->mime_parts[$part])
915    return '';
916   
917  $part = $MESSAGE->mime_parts[$part];
918  $table = new html_table(array('cols' => 3));
919 
920  if (!empty($part->filename)) {
921    $table->add('title', Q(rcube_label('filename')));
922    $table->add(null, Q($part->filename));
923    $table->add(null, '[' . html::a('?'.str_replace('_frame=', '_download=', $_SERVER['QUERY_STRING']), Q(rcube_label('download'))) . ']');
924  }
925 
926  if (!empty($part->size)) {
927    $table->add('title', Q(rcube_label('filesize')));
928    $table->add(null, Q(show_bytes($part->size)));
929  }
930 
931  return $table->show($attrib);
932  }
933
934
935
936function rcmail_message_part_frame($attrib)
937  {
938  global $MESSAGE;
939 
940  $part = $MESSAGE->mime_parts[asciiwords(get_input_value('_part', RCUBE_INPUT_GPC))];
941  $ctype_primary = strtolower($part->ctype_primary);
942
943  $attrib['src'] = Q('./?'.str_replace('_frame=', ($ctype_primary=='text' ? '_show=' : '_preload='), $_SERVER['QUERY_STRING']));
944
945  $attrib_str = create_attrib_string($attrib, array('id', 'class', 'style', 'src', 'width', 'height'));
946  $out = '<iframe '. $attrib_str . "></iframe>";
947   
948  return $out;
949  }
950
951
952/**
953 * clear message composing settings
954 */
955function rcmail_compose_cleanup()
956  {
957  if (!isset($_SESSION['compose']))
958    return;
959
960  // remove attachment files from temp dir
961  if (is_array($_SESSION['compose']['attachments']))
962    foreach ($_SESSION['compose']['attachments'] as $attachment)
963      @unlink($attachment['path']);
964 
965  unset($_SESSION['compose']);
966  }
967 
968
969/**
970 * Send the given message compose object using the configured method
971 */
972function rcmail_deliver_message(&$message, $from, $mailto)
973{
974  global $CONFIG;
975
976  $msg_body = $message->get();
977  $headers = $message->headers();
978 
979  // send thru SMTP server using custom SMTP library
980  if ($CONFIG['smtp_server'])
981    {
982    // generate list of recipients
983    $a_recipients = array($mailto);
984 
985    if (strlen($headers['Cc']))
986      $a_recipients[] = $headers['Cc'];
987    if (strlen($headers['Bcc']))
988      $a_recipients[] = $headers['Bcc'];
989 
990    // clean Bcc from header for recipients
991    $send_headers = $headers;
992    unset($send_headers['Bcc']);
993    // here too, it because txtHeaders() below use $message->_headers not only $send_headers
994    unset($message->_headers['Bcc']);
995
996    // send message
997    $smtp_response = array();
998    $sent = smtp_mail($from, $a_recipients, ($foo = $message->txtHeaders($send_headers, true)), $msg_body, $smtp_response);
999
1000    // log error
1001    if (!$sent)
1002      raise_error(array('code' => 800, 'type' => 'smtp', 'line' => __LINE__, 'file' => __FILE__,
1003                        'message' => "SMTP error: ".join("\n", $smtp_response)), TRUE, FALSE);
1004    }
1005 
1006  // send mail using PHP's mail() function
1007  else
1008    {
1009    // unset some headers because they will be added by the mail() function
1010    $headers_enc = $message->headers($headers);
1011    $headers_php = $message->_headers;
1012    unset($headers_php['To'], $headers_php['Subject']);
1013   
1014    // reset stored headers and overwrite
1015    $message->_headers = array();
1016    $header_str = $message->txtHeaders($headers_php);
1017 
1018    if (ini_get('safe_mode'))
1019      $sent = mail($headers_enc['To'], $headers_enc['Subject'], $msg_body, $header_str);
1020    else
1021      $sent = mail($headers_enc['To'], $headers_enc['Subject'], $msg_body, $header_str, "-f$from");
1022    }
1023 
1024  if ($sent)  // remove MDN headers after sending
1025    unset($headers['Return-Receipt-To'], $headers['Disposition-Notification-To']);
1026 
1027  $message->_headers = array();
1028  $message->headers($headers);
1029 
1030  return $sent;
1031}
1032
1033
1034function rcmail_send_mdn($uid)
1035{
1036  global $CONFIG, $USER, $IMAP;
1037
1038  $message = new rcube_message($uid);
1039 
1040  if ($message->headers->mdn_to && !$message->headers->mdn_sent)
1041  {
1042    $identity = $USER->get_identity();
1043    $sender = format_email_recipient($identity['email'], $identity['name']);
1044    $recipient = array_shift($IMAP->decode_address_list($message->headers->mdn_to));
1045    $mailto = $recipient['mailto'];
1046
1047    $compose = new rcube_mail_mime(rcmail_header_delm());
1048    $compose->setParam(array(
1049      'text_encoding' => 'quoted-printable',
1050      'html_encoding' => 'quoted-printable',
1051      'head_encoding' => 'quoted-printable',
1052      'head_charset'  => RCMAIL_CHARSET,
1053      'html_charset'  => RCMAIL_CHARSET,
1054      'text_charset'  => RCMAIL_CHARSET,
1055    ));
1056   
1057    // compose headers array
1058    $headers = array(
1059      'Date' => date('r'),
1060      'From' => $sender,
1061      'To'   => $message->headers->mdn_to,
1062      'Subject' => rcube_label('receiptread') . ': ' . $message->subject,
1063      'Message-ID' => sprintf('<%s@%s>', md5(uniqid('rcmail'.rand(),true)), rcmail_mail_domain($_SESSION['imap_host'])),
1064      'X-Sender' => $identity['email'],
1065      'Content-Type' => 'multipart/report; report-type=disposition-notification',
1066    );
1067   
1068    if (!empty($CONFIG['useragent']))
1069      $headers['User-Agent'] = $CONFIG['useragent'];
1070
1071    $body = rcube_label("yourmessage") . "\r\n\r\n" .
1072      "\t" . rcube_label("to") . ': ' . rcube_imap::decode_mime_string($message->headers->to, $message->headers->charset) . "\r\n" .
1073      "\t" . rcube_label("subject") . ': ' . $message->subject . "\r\n" .
1074      "\t" . rcube_label("sent") . ': ' . format_date($message->headers->date, $CONFIG['date_long']) . "\r\n" .
1075      "\r\n" . rcube_label("receiptnote") . "\r\n";
1076   
1077    $ua = !empty($CONFIG['useragent']) ? $CONFIG['useragent'] : "RoundCube Webmail (Version ".RCMAIL_VERSION.")";
1078    $report = "Reporting-UA: $ua\r\n";
1079   
1080    if ($message->headers->to)
1081        $report .= "Original-Recipient: {$message->headers->to}\r\n";
1082   
1083    $report .= "Final-Recipient: rfc822; {$identity['email']}\r\n" .
1084               "Original-Message-ID: {$message->headers->messageID}\r\n" .
1085               "Disposition: manual-action/MDN-sent-manually; displayed\r\n";
1086   
1087    $compose->headers($headers);
1088    $compose->setTXTBody(wordwrap($body, 75, "\r\n"));
1089    $compose->addAttachment($report, 'message/disposition-notification', 'MDNPart2.txt', false, '7bit', 'inline');
1090
1091    $sent = rcmail_deliver_message($compose, $identity['email'], $mailto);
1092
1093    if ($sent)
1094    {
1095      $IMAP->set_flag($message->uid, 'MDNSENT');
1096      return true;
1097    }
1098  }
1099 
1100  return false;
1101}
1102
1103
1104// register UI objects
1105$OUTPUT->add_handlers(array(
1106  'mailboxlist' => 'rcmail_mailbox_list',
1107  'messages' => 'rcmail_message_list',
1108  'messagecountdisplay' => 'rcmail_messagecount_display',
1109  'quotadisplay' => 'rcmail_quota_display',
1110  'messageheaders' => 'rcmail_message_headers',
1111  'messagebody' => 'rcmail_message_body',
1112  'messagecontentframe' => 'rcmail_messagecontent_frame',
1113  'messagepartframe' => 'rcmail_message_part_frame',
1114  'messagepartcontrols' => 'rcmail_message_part_controls',
1115  'searchform' => array($OUTPUT, 'search_form'),
1116));
1117
1118?>
Note: See TracBrowser for help on using the repository browser.