source: github/program/steps/mail/func.inc @ 2f93b03

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

condense TinyMCE toolbar down to one line, removing table buttons (#1484747)
fix image removal in message display when message HTML includes JS event handlers

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