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

HEADcourier-fixdev-browser-capabilitiespdorelease-0.6release-0.7release-0.8
Last change on this file since e559232 was e559232, checked in by alecpl <alec@…>, 3 years ago
  • fix white character after closing tag
  • Property mode set to 100644
File size: 47.6 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-2010, 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
22// setup some global vars used by mail steps
23$SENT_MBOX = $RCMAIL->config->get('sent_mbox');
24$DRAFTS_MBOX = $RCMAIL->config->get('drafts_mbox');
25$SEARCH_MODS_DEFAULT = array('*' => array('subject'=>1, 'from'=>1), $SENT_MBOX => array('subject'=>1, 'to'=>1), $DRAFTS_MBOX => array('subject'=>1, 'to'=>1));
26
27$EMAIL_ADDRESS_PATTERN = '([a-z0-9][a-z0-9\-\.\+\_]*@[a-z0-9][a-z0-9\-\.]*\\.[a-z]{2,5})';
28
29// actions that do not require imap connection
30$NOIMAP_ACTIONS = array('addcontact', 'autocomplete', 'upload', 'display-attachment', 'remove-attachment');
31
32// always instantiate imap object (but not yet connect to server)
33$RCMAIL->imap_init();
34
35// log in to imap server
36if (!in_array($RCMAIL->action, $NOIMAP_ACTIONS) && !$RCMAIL->imap_connect()) {
37  $RCMAIL->kill_session();
38
39  if ($OUTPUT->ajax_call)
40    $OUTPUT->redirect(array(), 2000);
41
42  $OUTPUT->set_env('task', 'login');
43  $OUTPUT->send('login');
44}
45
46// set imap properties and session vars
47if ($mbox = get_input_value('_mbox', RCUBE_INPUT_GPC))
48  $IMAP->set_mailbox(($_SESSION['mbox'] = $mbox));
49else if ($IMAP)
50  $_SESSION['mbox'] = $IMAP->get_mailbox_name();
51
52if (!empty($_GET['_page']))
53  $IMAP->set_page(($_SESSION['page'] = intval($_GET['_page'])));
54
55// set default sort col/order to session
56if (!isset($_SESSION['sort_col']))
57  $_SESSION['sort_col'] = $CONFIG['message_sort_col'];
58if (!isset($_SESSION['sort_order']))
59  $_SESSION['sort_order'] = $CONFIG['message_sort_order'];
60
61// set threads mode
62$a_threading = $RCMAIL->config->get('message_threading', array());
63if (isset($_GET['_threads'])) {
64  if ($_GET['_threads'])
65    $a_threading[$_SESSION['mbox']] = true;
66  else
67    unset($a_threading[$_SESSION['mbox']]);
68  $RCMAIL->user->save_prefs(array('message_threading' => $a_threading));
69}
70$IMAP->set_threading($a_threading[$_SESSION['mbox']]);
71
72// set message set for search result
73if (!empty($_REQUEST['_search']) && isset($_SESSION['search'][$_REQUEST['_search']]))
74  {
75  $IMAP->set_search_set($_SESSION['search'][$_REQUEST['_search']]);
76  $OUTPUT->set_env('search_request', $_REQUEST['_search']);
77  $OUTPUT->set_env('search_text', $_SESSION['last_text_search']);
78  }
79
80// set main env variables, labels and page title
81if (empty($RCMAIL->action) || $RCMAIL->action == 'list')
82  {
83  $mbox_name = $IMAP->get_mailbox_name();
84
85  if (empty($RCMAIL->action))
86    {
87    // initialize searching result if search_filter is used
88    if ($_SESSION['search_filter'] && $_SESSION['search_filter'] != 'ALL')
89      {
90      $search_request = md5($mbox_name.$_SESSION['search_filter']);
91
92      $IMAP->search($mbox_name, $_SESSION['search_filter'], RCMAIL_CHARSET, $_SESSION['sort_col']);
93      $_SESSION['search'][$search_request] = $IMAP->get_search_set();
94      $OUTPUT->set_env('search_request', $search_request);
95      }
96
97      $search_mods = $RCMAIL->config->get('search_mods', $SEARCH_MODS_DEFAULT);
98      $OUTPUT->set_env('search_mods', $search_mods);
99    }
100
101  // set current mailbox and some other vars in client environment
102  $OUTPUT->set_env('mailbox', $mbox_name);
103  $OUTPUT->set_env('pagesize', $IMAP->page_size);
104  $OUTPUT->set_env('quota', $IMAP->get_capability('quota'));
105  $OUTPUT->set_env('delimiter', $IMAP->get_hierarchy_delimiter());
106  $OUTPUT->set_env('threading', (bool) $IMAP->threading);
107  $OUTPUT->set_env('threads', $IMAP->threading
108        || $IMAP->get_capability('thread=references')
109        || $IMAP->get_capability('thread=orderedsubject')
110        || $IMAP->get_capability('thread=refs') 
111  );
112
113  if ($CONFIG['flag_for_deletion'])
114    $OUTPUT->set_env('flag_for_deletion', true);
115  if ($CONFIG['read_when_deleted'])
116    $OUTPUT->set_env('read_when_deleted', true);
117  if ($CONFIG['skip_deleted'])
118    $OUTPUT->set_env('skip_deleted', true);
119  if ($CONFIG['display_next'])
120    $OUTPUT->set_env('display_next', true);
121
122  $OUTPUT->set_env('preview_pane_mark_read', $RCMAIL->config->get('preview_pane_mark_read', 0));
123
124  if ($CONFIG['trash_mbox'])
125    $OUTPUT->set_env('trash_mailbox', $CONFIG['trash_mbox']);
126  if ($CONFIG['drafts_mbox'])
127    $OUTPUT->set_env('drafts_mailbox', $CONFIG['drafts_mbox']);
128  if ($CONFIG['junk_mbox'])
129    $OUTPUT->set_env('junk_mailbox', $CONFIG['junk_mbox']);
130
131  if (!$OUTPUT->ajax_call)
132    $OUTPUT->add_label('checkingmail', 'deletemessage', 'movemessagetotrash',
133      'movingmessage', 'copyingmessage', 'copy', 'move');
134
135  $OUTPUT->set_pagetitle(rcmail_localize_foldername($mbox_name));
136  }
137
138
139/**
140 * return the message list as HTML table
141 */
142function rcmail_message_list($attrib)
143{
144  global $IMAP, $CONFIG, $OUTPUT;
145
146  // add some labels to client
147  $OUTPUT->add_label('from', 'to');
148
149  // add id to message list table if not specified
150  if (!strlen($attrib['id']))
151    $attrib['id'] = 'rcubemessagelist';
152
153  // define list of cols to be displayed based on parameter or config
154  if (empty($attrib['columns'])) {
155    $a_show_cols = is_array($CONFIG['list_cols']) ? $CONFIG['list_cols'] : array('subject');
156    $OUTPUT->set_env('col_movable', !in_array('list_cols', (array)$CONFIG['dont_override']));
157  }
158  else {
159    $a_show_cols = preg_split('/[\s,;]+/', strip_quotes($attrib['columns']));
160    $attrib['columns'] = $a_show_cols;
161  }
162
163  // save some variables for use in ajax list
164  $_SESSION['list_attrib'] = $attrib;
165
166  $mbox = $IMAP->get_mailbox_name();
167  $delim = $IMAP->get_hierarchy_delimiter();
168
169  // show 'to' instead of 'from' in sent/draft messages
170  if ((strpos($mbox.$delim, $CONFIG['sent_mbox'].$delim)===0 || strpos($mbox.$delim, $CONFIG['drafts_mbox'].$delim)===0)
171      && (($f = array_search('from', $a_show_cols)) !== false) && array_search('to', $a_show_cols) === false)
172    $a_show_cols[$f] = 'to';
173
174  $skin_path = $_SESSION['skin_path'] = $CONFIG['skin_path'];
175
176  // set client env
177  $OUTPUT->add_gui_object('messagelist', $attrib['id']);
178  $OUTPUT->set_env('autoexpand_threads', intval($CONFIG['autoexpand_threads']));
179  $OUTPUT->set_env('sort_col', $_SESSION['sort_col']);
180  $OUTPUT->set_env('sort_order', $_SESSION['sort_order']);
181
182  if ($attrib['messageicon'])
183    $OUTPUT->set_env('messageicon', $skin_path . $attrib['messageicon']);
184  if ($attrib['deletedicon'])
185    $OUTPUT->set_env('deletedicon', $skin_path . $attrib['deletedicon']);
186  if ($attrib['unreadicon'])
187    $OUTPUT->set_env('unreadicon', $skin_path . $attrib['unreadicon']);
188  if ($attrib['repliedicon'])
189    $OUTPUT->set_env('repliedicon', $skin_path . $attrib['repliedicon']);
190  if ($attrib['forwardedicon'])
191    $OUTPUT->set_env('forwardedicon', $skin_path . $attrib['forwardedicon']);
192  if ($attrib['forwardedrepliedicon'])
193    $OUTPUT->set_env('forwardedrepliedicon', $skin_path . $attrib['forwardedrepliedicon']);
194  if ($attrib['attachmenticon'])
195    $OUTPUT->set_env('attachmenticon', $skin_path . $attrib['attachmenticon']);
196  if ($attrib['flaggedicon'])
197    $OUTPUT->set_env('flaggedicon', $skin_path . $attrib['flaggedicon']);
198  if ($attrib['unflaggedicon'])
199    $OUTPUT->set_env('unflaggedicon', $skin_path . $attrib['unflaggedicon']);
200  if ($attrib['unreadchildrenicon'])
201    $OUTPUT->set_env('unreadchildrenicon', $skin_path . $attrib['unreadchildrenicon']);
202
203  $OUTPUT->set_env('messages', array());
204  $OUTPUT->set_env('coltypes', $a_show_cols);
205
206  $OUTPUT->include_script('list.js');
207
208  $thead = '';
209  foreach (rcmail_message_list_head($attrib, $a_show_cols) as $cell)
210    $thead .= html::tag('td', array('class' => $cell['className'], 'id' => $cell['id']), $cell['html']);
211
212  return html::tag('table',
213    $attrib,
214    html::tag('thead', null, html::tag('tr', null, $thead)) .
215      html::tag('tbody', null, ''),
216        array('style', 'class', 'id', 'cellpadding', 'cellspacing', 'border', 'summary'));
217}
218
219
220/**
221 * return javascript commands to add rows to the message list
222 * or to replace the whole list (IE only)
223 */
224function rcmail_js_message_list($a_headers, $insert_top=FALSE, $head_replace=FALSE)
225{
226  global $CONFIG, $IMAP, $OUTPUT;
227
228  if (!empty($_SESSION['list_attrib']['columns']))
229    $a_show_cols = $_SESSION['list_attrib']['columns'];
230  else
231    $a_show_cols = is_array($CONFIG['list_cols']) ? $CONFIG['list_cols'] : array('subject');
232
233  $mbox = $IMAP->get_mailbox_name();
234  $delim = $IMAP->get_hierarchy_delimiter();
235
236  // show 'to' instead of 'from' in sent/draft messages
237  if ((strpos($mbox.$delim, $CONFIG['sent_mbox'].$delim)===0 || strpos($mbox.$delim, $CONFIG['drafts_mbox'].$delim)===0)
238      && (($f = array_search('from', $a_show_cols)) !== false) && array_search('to', $a_show_cols) === false)
239    $a_show_cols[$f] = 'to';
240
241  $thead = $head_replace ? rcmail_message_list_head($_SESSION['list_attrib'], $a_show_cols) : NULL;
242
243  $OUTPUT->command('set_message_coltypes', $a_show_cols, $thead);
244
245  if (empty($a_headers))
246    return;
247
248  // remove 'attachment' and 'flag' columns, we don't need them here
249  if(($key = array_search('attachment', $a_show_cols)) !== FALSE)
250    unset($a_show_cols[$key]);
251  if(($key = array_search('flag', $a_show_cols)) !== FALSE)
252    unset($a_show_cols[$key]);
253
254  // loop through message headers
255  foreach ($a_headers as $n => $header)
256    {
257    $a_msg_cols = array();
258    $a_msg_flags = array();
259
260    if (empty($header))
261      continue;
262
263    $IMAP->set_charset(!empty($header->charset) ? $header->charset : $CONFIG['default_charset']);
264
265    // format each col; similar as in rcmail_message_list()
266    foreach ($a_show_cols as $col)
267      {
268      if (in_array($col, array('from', 'to', 'cc', 'replyto')))
269        $cont = Q(rcmail_address_string($header->$col, 3), 'show');
270      else if ($col=='subject')
271        {
272        $cont = abbreviate_string(trim($IMAP->decode_header($header->$col)), 160);
273        if (!$cont) $cont = rcube_label('nosubject');
274        $cont = Q($cont);
275        }
276      else if ($col=='size')
277        $cont = show_bytes($header->$col);
278      else if ($col=='date')
279        $cont = format_date($header->date);
280      else
281        $cont = Q($header->$col);
282
283      $a_msg_cols[$col] = $cont;
284      }
285
286    if ($header->depth)
287      $a_msg_flags['depth'] = $header->depth;
288    else if ($header->has_children)
289      $roots[] = $header->uid;
290    if ($header->parent_uid)
291      $a_msg_flags['parent_uid'] = $header->parent_uid;
292    if ($header->has_children)
293      $a_msg_flags['has_children'] = $header->has_children;
294    if ($header->unread_children)
295      $a_msg_flags['unread_children'] = $header->unread_children;
296    if ($header->deleted)
297      $a_msg_flags['deleted'] = 1;
298    if (!$header->seen)
299      $a_msg_flags['unread'] = 1;
300    if ($header->answered)
301      $a_msg_flags['replied'] = 1;
302    if ($header->forwarded)
303      $a_msg_flags['forwarded'] = 1;
304    if ($header->flagged)
305      $a_msg_flags['flagged'] = 1;
306    if(preg_match("/multipart\/m/i", $header->ctype))
307      $a_msg_flags['attachment'] = 1;
308    $a_msg_flags['mbox'] = $mbox;
309
310    $OUTPUT->command('add_message_row',
311      $header->uid,
312      $a_msg_cols,
313      $a_msg_flags,
314      $insert_top);
315    }
316
317    if ($IMAP->threading && $a_headers) {
318      $OUTPUT->command('init_threads', (array) $roots);
319    }
320}
321
322
323/*
324 * Creates <THEAD> for message list table
325 */
326function rcmail_message_list_head($attrib, $a_show_cols)
327{
328  global $CONFIG;
329
330  $skin_path = $_SESSION['skin_path'];
331  $image_tag = html::img(array('src' => "%s%s", 'alt' => "%s"));
332
333  // check to see if we have some settings for sorting
334  $sort_col   = $_SESSION['sort_col'];
335  $sort_order = $_SESSION['sort_order'];
336
337  // define sortable columns
338  $a_sort_cols = array('subject', 'date', 'from', 'to', 'size', 'cc');
339
340  if (!empty($attrib['optionsmenuicon']))
341    $list_menu = html::a(
342      array('href' => '#', 'onclick' => 'return '.JS_OBJECT_NAME.".command('menu-open', 'messagelistmenu')"),
343      html::img(array('src' => $skin_path . $attrib['optionsmenuicon'], 'id' => 'listmenulink', 'title' => rcube_label('listoptions')))
344    );
345  else
346    $list_menu = '';
347
348  $cells = array(array('className' => 'threads', 'html' => $list_menu));
349
350  foreach ($a_show_cols as $col) {
351    // get column name
352    switch ($col) {
353      case 'flag':
354        $col_name = sprintf($image_tag, $skin_path, $attrib['unflaggedicon'], '');
355        break;
356      case 'attachment':
357        $col_name = sprintf($image_tag, $skin_path, $attrib['attachmenticon'], '');
358        break;
359      default:
360        $col_name = Q(rcube_label($col));
361    }
362
363    // make sort links
364    if (in_array($col, $a_sort_cols))
365      $col_name = html::a(array('href'=>"./#sort", 'onclick' => 'return '.JS_OBJECT_NAME.".command('sort','".$col."',this)", 'title' => rcube_label('sortby')), $col_name);
366
367    $sort_class = $col == $sort_col ? " sorted$sort_order" : '';
368    $class_name = $col == 'attachment' ? 'icon' : $col.$sort_class;
369
370    // put it all together
371    $cells[] = array('className' => $class_name, 'id' => "rcm$col", 'html' => $col_name);
372  }
373
374  return $cells;
375}
376
377
378/**
379 * return an HTML iframe for loading mail content
380 */
381function rcmail_messagecontent_frame($attrib)
382  {
383  global $OUTPUT;
384
385  if (empty($attrib['id']))
386    $attrib['id'] = 'rcmailcontentwindow';
387
388  $attrib['name'] = $attrib['id'];
389
390  $OUTPUT->set_env('contentframe', $attrib['id']);
391  $OUTPUT->set_env('blankpage', $attrib['src'] ? $OUTPUT->abs_url($attrib['src']) : 'program/blank.gif');
392
393  return html::iframe($attrib);
394  }
395
396
397function rcmail_messagecount_display($attrib)
398  {
399  global $IMAP, $OUTPUT;
400
401  if (!$attrib['id'])
402    $attrib['id'] = 'rcmcountdisplay';
403
404  $OUTPUT->add_gui_object('countdisplay', $attrib['id']);
405
406  return html::span($attrib, rcmail_get_messagecount_text());
407  }
408
409
410function rcmail_quota_display($attrib)
411  {
412  global $OUTPUT;
413
414  if (!$attrib['id'])
415    $attrib['id'] = 'rcmquotadisplay';
416
417  if(isset($attrib['display']))
418    $_SESSION['quota_display'] = $attrib['display'];
419
420  $OUTPUT->add_gui_object('quotadisplay', $attrib['id']);
421
422  $quota = rcmail_quota_content($attrib);
423
424  if (is_array($quota)) {
425    $OUTPUT->add_script('$(document).ready(function(){
426        rcmail.set_quota('.json_serialize($quota).')});', 'foot');
427    $quota = '';
428    }
429
430  return html::span($attrib, $quota);
431  }
432
433
434function rcmail_quota_content($attrib=NULL)
435  {
436  global $COMM_PATH, $RCMAIL;
437
438  $display = isset($_SESSION['quota_display']) ? $_SESSION['quota_display'] : '';
439
440  $quota = $RCMAIL->imap->get_quota();
441  $quota = $RCMAIL->plugins->exec_hook('quota', $quota);
442
443  if (!$quota['total'] && $RCMAIL->config->get('quota_zero_as_unlimited'))
444    return rcube_label('unlimited');
445
446  if ($quota['total'])
447    {
448    if (!isset($quota['percent']))
449      $quota['percent'] = min(100, round(($quota['used']/max(1,$quota['total']))*100));
450
451    $quota_result = sprintf('%s / %s (%.0f%%)',
452        show_bytes($quota['used'] * 1024), show_bytes($quota['total'] * 1024),
453        $quota['percent']);
454
455    if ($display == 'image') {
456      $quota_result = array(
457        'percent'       => $quota['percent'],
458        'title'         => $quota_result,
459          );
460
461      if ($attrib['width'])
462        $quota_result['width'] = $attrib['width'];
463      if ($attrib['height'])
464        $quota_result['height'] = $attrib['height'];
465      }
466
467      return $quota_result;
468    }
469
470  return rcube_label('unknown');
471  }
472
473
474function rcmail_get_messagecount_text($count=NULL, $page=NULL)
475  {
476  global $RCMAIL, $IMAP, $MESSAGE;
477
478  if (isset($MESSAGE->index))
479    {
480    return rcube_label(array('name' => 'messagenrof',
481        'vars' => array('nr'  => $MESSAGE->index+1,
482        'count' => $count!==NULL ? $count : $IMAP->messagecount(NULL, 'ALL')))); // Only messages, no threads here
483    }
484
485  if ($page===NULL)
486    $page = $IMAP->list_page;
487
488  $start_msg = ($page-1) * $IMAP->page_size + 1;
489
490  if ($count!==NULL)
491    $max = $count;
492  else if ($RCMAIL->action)
493    $max = $IMAP->messagecount(NULL, $IMAP->threading ? 'THREADS' : 'ALL');
494
495  if ($max==0)
496    $out = rcube_label('mailboxempty');
497  else
498    $out = rcube_label(array('name' => $IMAP->threading ? 'threadsfromto' : 'messagesfromto',
499            'vars' => array('from'  => $start_msg,
500            'to'    => min($max, $start_msg + $IMAP->page_size - 1),
501            'count' => $max)));
502
503  return Q($out);
504  }
505
506
507function rcmail_mailbox_name_display($attrib)
508{
509  global $RCMAIL;
510
511  if (!$attrib['id'])
512    $attrib['id'] = 'rcmmailboxname';
513
514  $RCMAIL->output->add_gui_object('mailboxname', $attrib['id']);
515
516  return html::span($attrib, rcmail_get_mailbox_name_text());
517}
518
519
520function rcmail_get_mailbox_name_text()
521{
522  global $RCMAIL;
523  return rcmail_localize_foldername($RCMAIL->imap->get_mailbox_name());
524}
525
526
527function rcmail_send_unread_count($mbox_name, $force=false)
528{
529  global $RCMAIL;
530
531  $old_unseen = $_SESSION['unseen_count'][$mbox_name];
532  $unseen = $RCMAIL->imap->messagecount($mbox_name, 'UNSEEN', $force);
533
534  if ($unseen != $old_unseen || ($mbox_name == 'INBOX'))
535    $RCMAIL->output->command('set_unread_count', $mbox_name, $unseen, ($mbox_name == 'INBOX'));
536
537  // @TODO: this data is doubled (session and cache tables) if caching is enabled
538  $_SESSION['unseen_count'][$mbox_name] = $unseen;
539
540  return $unseen;
541}
542
543
544/**
545 * Sets message is_safe flag according to 'show_images' option value
546 *
547 * @param object rcube_message Message
548 */
549function rcmail_check_safe(&$message)
550{
551  global $RCMAIL;
552
553  $show_images = $RCMAIL->config->get('show_images');
554  if (!$message->is_safe
555    && !empty($show_images)
556    && $message->has_html_part())
557  {
558    switch($show_images) {
559      case '1': // known senders only
560        $CONTACTS = new rcube_contacts($RCMAIL->db, $_SESSION['user_id']);
561        if ($CONTACTS->search('email', $message->sender['mailto'], true, false)->count) {
562          $message->set_safe(true);
563        }
564      break;
565      case '2': // always
566        $message->set_safe(true);
567      break;
568    }
569  }
570}
571
572
573/**
574 * Cleans up the given message HTML Body (for displaying)
575 *
576 * @param string HTML
577 * @param array  Display parameters
578 * @param array  CID map replaces (inline images)
579 * @return string Clean HTML
580 */
581function rcmail_wash_html($html, $p = array(), $cid_replaces)
582{
583  global $REMOTE_OBJECTS;
584
585  $p += array('safe' => false, 'inline_html' => true);
586
587  // special replacements (not properly handled by washtml class)
588  $html_search = array(
589    '/(<\/nobr>)(\s+)(<nobr>)/i',       // space(s) between <NOBR>
590    '/<title[^>]*>.*<\/title>/i',       // PHP bug #32547 workaround: remove title tag
591    '/^(\0\0\xFE\xFF|\xFF\xFE\0\0|\xFE\xFF|\xFF\xFE|\xEF\xBB\xBF)/',    // byte-order mark (only outlook?)
592    '/<html\s[^>]+>/i',                 // washtml/DOMDocument cannot handle xml namespaces
593  );
594  $html_replace = array(
595    '\\1'.' &nbsp; '.'\\3',
596    '',
597    '',
598    '<html>',
599  );
600  $html = preg_replace($html_search, $html_replace, $html);
601
602  // fix (unknown/malformed) HTML tags before "wash"
603  $html = preg_replace_callback('/(<[\/]*)([^\s>]+)/', 'rcmail_html_tag_callback', $html);
604
605  // charset was converted to UTF-8 in rcube_imap::get_message_part(),
606  // -> change charset specification in HTML accordingly
607  $charset_pattern = '(<meta\s+[^>]* content=)[\'"]?(\w+\/\w+;\s*charset=)([a-z0-9-_]+[\'"]?)';
608  if (preg_match("/$charset_pattern/Ui", $html)) {
609    $html = preg_replace("/$charset_pattern/i", '\\1"\\2'.RCMAIL_CHARSET.'"', $html);
610  }
611  else {
612    // add meta content-type to malformed messages, washtml cannot work without that
613    if (!preg_match('/<head[^>]*>(.*)<\/head>/Uims', $html))
614      $html = '<head></head>'. $html;
615    $html = substr_replace($html, '<meta http-equiv="Content-Type" content="text/html; charset='.RCMAIL_CHARSET.'" />', intval(stripos($html, '<head>')+6), 0);
616  }
617
618  // turn relative into absolute urls
619  $html = rcmail_resolve_base($html);
620
621  // clean HTML with washhtml by Frederic Motte
622  $wash_opts = array(
623    'show_washed' => false,
624    'allow_remote' => $p['safe'],
625    'blocked_src' => "./program/blocked.gif",
626    'charset' => RCMAIL_CHARSET,
627    'cid_map' => $cid_replaces,
628    'html_elements' => array('body'),
629  );
630
631  if (!$p['inline_html']) {
632    $wash_opts['html_elements'] = array('html','head','title','body');
633  }
634  if ($p['safe']) {
635    $wash_opts['html_elements'][] = 'link';
636    $wash_opts['html_attribs'] = array('rel','type');
637  }
638
639  $washer = new washtml($wash_opts);
640  $washer->add_callback('form', 'rcmail_washtml_callback');
641
642  // allow CSS styles, will be sanitized by rcmail_washtml_callback()
643  $washer->add_callback('style', 'rcmail_washtml_callback');
644
645  $html = $washer->wash($html);
646  $REMOTE_OBJECTS = $washer->extlinks;
647
648  return $html;
649}
650
651
652/**
653 * Convert the given message part to proper HTML
654 * which can be displayed the message view
655 *
656 * @param object rcube_message_part Message part
657 * @param array  Display parameters array
658 * @return string Formatted HTML string
659 */
660function rcmail_print_body($part, $p = array())
661{
662  global $RCMAIL;
663
664  // trigger plugin hook
665  $data = $RCMAIL->plugins->exec_hook('message_part_before',
666    array('type' => $part->ctype_secondary, 'body' => $part->body) + $p + array('safe' => false, 'plain' => false, 'inline_html' => true));
667
668  // convert html to text/plain
669  if ($data['type'] == 'html' && $data['plain']) {
670    $txt = new html2text($data['body'], false, true);
671    $body = $txt->get_text();
672    $part->ctype_secondary = 'plain';
673  }
674  // text/html
675  else if ($data['type'] == 'html') {
676    $body = rcmail_wash_html($data['body'], $data, $part->replaces);
677    $part->ctype_secondary = $data['type'];
678  }
679  // text/enriched
680  else if ($data['type'] == 'enriched') {
681    $part->ctype_secondary = 'html';
682    require_once('lib/enriched.inc');
683    $body = Q(enriched_to_html($data['body']), 'show');
684  }
685  else {
686    // assert plaintext
687    $body = $part->body;
688    $part->ctype_secondary = $data['type'] = 'plain';
689  }
690
691  // free some memory (hopefully)
692  unset($data['body']);
693
694  // plaintext postprocessing
695  if ($part->ctype_secondary == 'plain')
696    $body = rcmail_plain_body($body);
697
698  // allow post-processing of the message body
699  $data = $RCMAIL->plugins->exec_hook('message_part_after', array('type' => $part->ctype_secondary, 'body' => $body) + $data);
700
701  return $data['type'] == 'html' ? $data['body'] : html::tag('pre', array(), $data['body']);
702}
703
704
705/**
706 * Handle links and citation marks in plain text message
707 *
708 * @param string  Plain text string
709 * @return string Formatted HTML string
710 */
711function rcmail_plain_body($body)
712{
713  // make links and email-addresses clickable
714  $replacements = new rcube_string_replacer;
715
716  // search for patterns like links and e-mail addresses
717  $body = preg_replace_callback($replacements->link_pattern, array($replacements, 'link_callback'), $body);
718  $body = preg_replace_callback($replacements->mailto_pattern, array($replacements, 'mailto_callback'), $body);
719
720  // split body into single lines
721  $a_lines = preg_split('/\r?\n/', $body);
722  $q_lines = array();
723  $quote_level = 0;
724
725  // find/mark quoted lines...
726  for ($n=0, $cnt=count($a_lines); $n < $cnt; $n++) {
727    $q = 0;
728
729    if ($a_lines[$n][0] == '>' && preg_match('/^(>+\s*)+/', $a_lines[$n], $regs)) {
730      $q = strlen(preg_replace('/\s/', '', $regs[0]));
731        $a_lines[$n] = substr($a_lines[$n], strlen($regs[0]));
732
733      if ($q > $quote_level)
734        $q_lines[$n]['quote'] = $q - $quote_level;
735      else if ($q < $quote_level)
736        $q_lines[$n]['endquote'] = $quote_level - $q;
737    }
738    else if ($quote_level > 0)
739      $q_lines[$n]['endquote'] = $quote_level;
740
741    $quote_level = $q;
742  }
743
744  // quote plain text
745  $body = Q(join("\n", $a_lines), 'replace', false);
746
747  // colorize signature
748  if (($sp = strrpos($body, '-- ')) !== false)
749    if (($sp == 0 || $body[$sp-1] == "\n") && $body[$sp+3] == "\n") {
750      $body = substr($body, 0, max(0, $sp))
751        .'<span class="sig">'.substr($body, $sp).'</span>';
752    }
753
754  // colorize quoted lines
755  $a_lines = preg_split('/\n/', $body);
756  foreach ($q_lines as $i => $q)
757    if ($q['quote'])
758      $a_lines[$i] = str_repeat('<blockquote>', $q['quote']) . $a_lines[$i];
759    else if ($q['endquote'])
760      $a_lines[$i] = str_repeat('</blockquote>', $q['endquote']) . $a_lines[$i];
761
762  // insert the links for urls and mailtos
763  $body = $replacements->resolve(join("\n", $a_lines));
764   
765  return $body;
766}
767
768
769/**
770 * add a string to the replacement array and return a replacement string
771 */
772function rcmail_str_replacement($str, &$rep)
773{
774  static $count = 0;
775  $rep[$count] = stripslashes($str);
776  return "##string_replacement{".($count++)."}##";
777}
778
779
780/**
781 * Callback function for washtml cleaning class
782 */
783function rcmail_washtml_callback($tagname, $attrib, $content)
784{
785  switch ($tagname) {
786    case 'form':
787      $out = html::div('form', $content);
788      break;
789
790    case 'style':
791      // decode all escaped entities and reduce to ascii strings
792      $stripped = preg_replace('/[^a-zA-Z\(:]/', '', rcmail_xss_entity_decode($content));
793
794      // now check for evil strings like expression, behavior or url()
795      if (!preg_match('/expression|behavior|url\(|import/', $stripped)) {
796        $out = html::tag('style', array('type' => 'text/css'), $content);
797        break;
798      }
799
800    default:
801      $out = '';
802  }
803
804  return $out;
805}
806
807
808/**
809 * Callback function for HTML tags fixing
810 */
811function rcmail_html_tag_callback($matches)
812{
813  $tagname = $matches[2];
814
815  $tagname = preg_replace(array(
816    '/:.*$/',                   // Microsoft's Smart Tags <st1:xxxx>
817    '/[^a-z0-9_\[\]\!-]/i',     // forbidden characters
818    ), '', $tagname);
819
820  return $matches[1].$tagname;
821}
822
823
824/**
825 * return table with message headers
826 */
827function rcmail_message_headers($attrib, $headers=NULL)
828  {
829  global $IMAP, $OUTPUT, $MESSAGE, $PRINT_MODE, $RCMAIL;
830  static $sa_attrib;
831
832  // keep header table attrib
833  if (is_array($attrib) && !$sa_attrib)
834    $sa_attrib = $attrib;
835  else if (!is_array($attrib) && is_array($sa_attrib))
836    $attrib = $sa_attrib;
837
838  if (!isset($MESSAGE))
839    return FALSE;
840
841  // get associative array of headers object
842  if (!$headers)
843    $headers = is_object($MESSAGE->headers) ? get_object_vars($MESSAGE->headers) : $MESSAGE->headers;
844
845  // show these headers
846  $standard_headers = array('subject', 'from', 'to', 'cc', 'bcc', 'replyto', 'date');
847  $output_headers = array();
848
849  foreach ($standard_headers as $hkey) {
850    if (!$headers[$hkey])
851      continue;
852
853    if ($hkey == 'date') {
854      if ($PRINT_MODE)
855        $header_value = format_date($headers[$hkey], $RCMAIL->config->get('date_long', 'x'));
856      else
857        $header_value = format_date($headers[$hkey]);
858    }
859    else if ($hkey == 'replyto') {
860      if ($headers['replyto'] != $headers['from'])
861        $header_value = rcmail_address_string($headers['replyto'], null, true, $attrib['addicon']);
862      else
863        continue;
864    }
865    else if (in_array($hkey, array('from', 'to', 'cc', 'bcc')))
866      $header_value = rcmail_address_string($headers[$hkey], null, true, $attrib['addicon']);
867    else if ($hkey == 'subject' && empty($headers[$hkey]))
868      $header_value = rcube_label('nosubject');
869    else
870      $header_value = trim($IMAP->decode_header($headers[$hkey]));
871
872    $output_headers[$hkey] = array('title' => rcube_label($hkey), 'value' => $header_value, 'raw' => $headers[$hkey]);
873  }
874
875  $plugin = $RCMAIL->plugins->exec_hook('message_headers_output', array('output' => $output_headers, 'headers' => $MESSAGE->headers));
876
877  // compose html table
878  $table = new html_table(array('cols' => 2));
879
880  foreach ($plugin['output'] as $hkey => $row) {
881    $table->add(array('class' => 'header-title'), Q($row['title']));
882    $table->add(array('class' => $hkey, 'width' => "90%"), Q($row['value'], ($hkey == 'subject' ? 'strict' : 'show')));
883  }
884
885  // all headers division
886  $table->add(array('colspan' => 2, 'class' => "more-headers show-headers", 'onclick' => "return ".JS_OBJECT_NAME.".command('load-headers','',this)"), '');
887  $table->add_row(array('id' => "all-headers"));
888  $table->add(array('colspan' => 2, 'class' => "all"), html::div(array('id' => 'headers-source'), ''));
889 
890  $OUTPUT->add_gui_object('all_headers_row', 'all-headers');
891  $OUTPUT->add_gui_object('all_headers_box', 'headers-source');
892
893  return $table->show($attrib);
894  }
895
896
897/**
898 * Handler for the 'messagebody' GUI object
899 *
900 * @param array Named parameters
901 * @return string HTML content showing the message body
902 */
903function rcmail_message_body($attrib)
904  {
905  global $CONFIG, $OUTPUT, $MESSAGE, $IMAP, $REMOTE_OBJECTS;
906
907  if (!is_array($MESSAGE->parts) && empty($MESSAGE->body))
908    return '';
909
910  if (!$attrib['id'])
911    $attrib['id'] = 'rcmailMsgBody';
912
913  $safe_mode = $MESSAGE->is_safe || intval($_GET['_safe']);
914  $out = '';
915
916  $header_attrib = array();
917  foreach ($attrib as $attr => $value)
918    if (preg_match('/^headertable([a-z]+)$/i', $attr, $regs))
919      $header_attrib[$regs[1]] = $value;
920
921  if (!empty($MESSAGE->parts))
922    {
923    foreach ($MESSAGE->parts as $i => $part)
924      {
925      if ($part->type == 'headers')
926        $out .= rcmail_message_headers(sizeof($header_attrib) ? $header_attrib : NULL, $part->headers);
927      else if ($part->type == 'content' && $part->size)
928        {
929        if (empty($part->ctype_parameters) || empty($part->ctype_parameters['charset']))
930          $part->ctype_parameters['charset'] = $MESSAGE->headers->charset;
931
932        // fetch part if not available
933        if (!isset($part->body))
934          $part->body = $MESSAGE->get_part_content($part->mime_id);
935
936        // re-format format=flowed content
937        if ($part->ctype_secondary == "plain" && $part->ctype_parameters['format'] == "flowed")
938          $part->body = rcube_message::unfold_flowed($part->body);
939
940        $body = rcmail_print_body($part, array('safe' => $safe_mode, 'plain' => !$CONFIG['prefer_html']));
941
942        if ($part->ctype_secondary == 'html')
943          $out .= html::div('message-htmlpart', rcmail_html4inline($body, $attrib['id'], 'div.rcmBody'));
944        else
945          $out .= html::div('message-part', $body);
946        }
947      }
948    }
949  else
950    $out .= html::div('message-part', html::tag('pre', array(),
951      rcmail_plain_body(Q($MESSAGE->body, 'strict', false))));
952
953  $ctype_primary = strtolower($MESSAGE->structure->ctype_primary);
954  $ctype_secondary = strtolower($MESSAGE->structure->ctype_secondary);
955
956  // list images after mail body
957  if ($CONFIG['inline_images']
958      && $ctype_primary == 'multipart'
959      && !empty($MESSAGE->attachments)
960      && !strstr($message_body, '<html'))
961    {
962    foreach ($MESSAGE->attachments as $attach_prop) {
963      if (strpos($attach_prop->mimetype, 'image/') === 0) {
964        $out .= html::tag('hr') . html::p(array('align' => "center"),
965          html::img(array(
966            'src' => $MESSAGE->get_part_url($attach_prop->mime_id),
967            'title' => $attach_prop->filename,
968            'alt' => $attach_prop->filename,
969          )));
970        }
971    }
972  }
973
974  // tell client that there are blocked remote objects
975  if ($REMOTE_OBJECTS && !$safe_mode)
976    $OUTPUT->set_env('blockedobjects', true);
977
978  return html::div($attrib, $out);
979  }
980
981
982/**
983 * Convert all relative URLs according to a <base> in HTML
984 */
985function rcmail_resolve_base($body)
986{
987  // check for <base href=...>
988  if (preg_match('!(<base.*href=["\']?)([hftps]{3,5}://[a-z0-9/.%-]+)!i', $body, $regs)) {
989    $replacer = new rcube_base_replacer($regs[2]);
990
991    // replace all relative paths
992    $body = preg_replace_callback('/(src|background|href)=(["\']?)([\.\/]+[^"\'\s]+)(\2|\s|>)/Ui', array($replacer, 'callback'), $body);
993    $body = preg_replace_callback('/(url\s*\()(["\']?)([\.\/]+[^"\'\)\s]+)(\2)\)/Ui', array($replacer, 'callback'), $body);
994  }
995
996  return $body;
997}
998
999/**
1000 * modify a HTML message that it can be displayed inside a HTML page
1001 */
1002function rcmail_html4inline($body, $container_id, $body_id='')
1003  {
1004  $last_style_pos = 0;
1005  $body_lc = strtolower($body);
1006
1007  // find STYLE tags
1008  while (($pos = strpos($body_lc, '<style', $last_style_pos)) && ($pos2 = strpos($body_lc, '</style>', $pos)))
1009    {
1010    $pos = strpos($body_lc, '>', $pos)+1;
1011
1012    // replace all css definitions with #container [def]
1013    $styles = rcmail_mod_css_styles(substr($body, $pos, $pos2-$pos), $container_id.($body_id ? ' '.$body_id : ''));
1014
1015    $body = substr($body, 0, $pos) . $styles . substr($body, $pos2);
1016    $body_lc = strtolower($body);
1017    $last_style_pos = $pos2;
1018    }
1019
1020  // modify HTML links to open a new window if clicked
1021  $GLOBALS['rcmail_html_container_id'] = $container_id;
1022  $body = preg_replace_callback('/<(a|link)\s+([^>]+)>/Ui', 'rcmail_alter_html_link', $body);
1023  unset($GLOBALS['rcmail_html_container_id']);
1024
1025  $out = preg_replace(array(
1026      // add comments arround html and other tags
1027      '/(<!DOCTYPE[^>]*>)/i',
1028      '/(<\?xml[^>]*>)/i',
1029      '/(<\/?html[^>]*>)/i',
1030      '/(<\/?head[^>]*>)/i',
1031      '/(<title[^>]*>.*<\/title>)/Ui',
1032      '/(<\/?meta[^>]*>)/i',
1033      // quote <? of php and xml files that are specified as text/html
1034      '/<\?/',
1035      '/\?>/',
1036      // replace <body> with <div>
1037      '/<body([^>]*)>/i',
1038      '/<\/body>/i',
1039      ),
1040    array(
1041      '<!--\\1-->',
1042      '<!--\\1-->',
1043      '<!--\\1-->',
1044      '<!--\\1-->',
1045      '<!--\\1-->',
1046      '<!--\\1-->',
1047      '&lt;?',
1048      '?&gt;',
1049      '<div class="rcmBody"\\1>',
1050      '</div>',
1051      ),
1052    $body);
1053
1054  // make sure there's 'rcmBody' div, we need it for proper css modification
1055  // its name is hardcoded in rcmail_message_body() also
1056  if (!preg_match('/<div class="rcmBody"/', $out))
1057    $out = '<div class="rcmBody">' . $out . '</div>';
1058
1059  return $out;
1060  }
1061
1062
1063/**
1064 * parse link attributes and set correct target
1065 */
1066function rcmail_alter_html_link($matches)
1067{
1068  global $EMAIL_ADDRESS_PATTERN;
1069
1070  $tag = $matches[1];
1071  $attrib = parse_attrib_string($matches[2]);
1072  $end = '>';
1073
1074  if ($tag == 'link' && preg_match('/^https?:\/\//i', $attrib['href'])) {
1075    $attrib['href'] = "?_task=utils&amp;_action=modcss&amp;u=" . urlencode($attrib['href'])
1076        . "&amp;c=" . urlencode($GLOBALS['rcmail_html_container_id']);
1077    $end = ' />';
1078  }
1079  else if (preg_match('/^mailto:'.$EMAIL_ADDRESS_PATTERN.'(\?[^"\'>]+)?/i', $attrib['href'], $mailto)) {
1080    $attrib['href'] = $mailto[0];
1081    $attrib['onclick'] = sprintf(
1082      "return %s.command('compose','%s',this)",
1083      JS_OBJECT_NAME,
1084      JQ($mailto[1].$mailto[2]));
1085  }
1086  else if (!empty($attrib['href']) && $attrib['href'][0] != '#') {
1087    $attrib['target'] = '_blank';
1088  }
1089
1090  return "<$tag" . html::attrib_string($attrib, array('href','name','target','onclick','id','class','style','title','rel','type','media')) . $end;
1091}
1092
1093
1094/**
1095 * decode address string and re-format it as HTML links
1096 */
1097function rcmail_address_string($input, $max=null, $linked=false, $addicon=null)
1098{
1099  global $IMAP, $RCMAIL, $PRINT_MODE, $CONFIG, $OUTPUT, $EMAIL_ADDRESS_PATTERN;
1100  static $got_writable_abook = null;
1101
1102  $a_parts = $IMAP->decode_address_list($input);
1103
1104  if (!sizeof($a_parts))
1105    return $input;
1106
1107  $c = count($a_parts);
1108  $j = 0;
1109  $out = '';
1110
1111  if ($got_writable_abook === null && $books = $RCMAIL->get_address_sources(true)) {
1112    $got_writable_abook = true;
1113  }
1114
1115  foreach ($a_parts as $part) {
1116    $j++;
1117    if ($PRINT_MODE) {
1118      $out .= sprintf('%s &lt;%s&gt;', Q($part['name']), $part['mailto']);
1119    }
1120    else if (check_email($part['mailto'], false)) {
1121      if ($linked) {
1122        $out .= html::a(array(
1123            'href' => 'mailto:'.$part['mailto'],
1124            'onclick' => sprintf("return %s.command('compose','%s',this)", JS_OBJECT_NAME, JQ($part['mailto'])),
1125            'title' => $part['mailto'],
1126            'class' => "rcmContactAddress",
1127          ),
1128        Q($part['name']));
1129      }
1130      else {
1131        $out .= html::span(array('title' => $part['mailto'], 'class' => "rcmContactAddress"), Q($part['name']));
1132      }
1133
1134      if ($addicon && $got_writable_abook) {
1135        $out .= '&nbsp;' . html::a(array(
1136            'href' => "#add",
1137            'onclick' => sprintf("return %s.command('add-contact','%s',this)", JS_OBJECT_NAME, urlencode($part['string'])),
1138            'title' => rcube_label('addtoaddressbook'),
1139          ),
1140          html::img(array(
1141            'src' => $CONFIG['skin_path'] . $addicon,
1142            'alt' => "Add contact",
1143          )));
1144      }
1145    }
1146    else {
1147      if ($part['name'])
1148        $out .= Q($part['name']);
1149      if ($part['mailto'])
1150        $out .= (strlen($out) ? ' ' : '') . sprintf('&lt;%s&gt;', Q($part['mailto']));
1151    }
1152
1153    if ($c>$j)
1154      $out .= ','.($max ? '&nbsp;' : ' ');
1155
1156    if ($max && $j==$max && $c>$j) {
1157      $out .= '...';
1158      break;
1159    }
1160  }
1161
1162  return $out;
1163}
1164
1165
1166/**
1167 * Wrap text to a given number of characters per line
1168 * but respect the mail quotation of replies messages (>).
1169 * Finally add another quotation level by prpending the lines
1170 * with >
1171 *
1172 * @param string Text to wrap
1173 * @param int The line width
1174 * @return string The wrapped text
1175 */
1176function rcmail_wrap_and_quote($text, $length = 72)
1177{
1178  // Rebuild the message body with a maximum of $max chars, while keeping quoted message.
1179  $max = min(77, $length + 8);
1180  $lines = preg_split('/\r?\n/', trim($text));
1181  $out = '';
1182
1183  foreach ($lines as $line) {
1184    // don't wrap already quoted lines
1185    if ($line[0] == '>')
1186      $line = '>' . rtrim($line);
1187    else if (mb_strlen($line) > $max) {
1188      $newline = '';
1189      foreach(explode("\n", rc_wordwrap($line, $length - 2)) as $l) {
1190        if (strlen($l))
1191          $newline .= '> ' . $l . "\n";
1192        else
1193          $newline .= ">\n";
1194      }
1195      $line = rtrim($newline);
1196    }
1197    else
1198      $line = '> ' . $line;
1199
1200    // Append the line
1201    $out .= $line . "\n";
1202  }
1203
1204  return $out;
1205}
1206
1207
1208function rcmail_draftinfo_encode($p)
1209{
1210  $parts = array();
1211  foreach ($p as $key => $val)
1212    $parts[] = $key . '=' . ($key == 'folder' ? base64_encode($val) : $val);
1213
1214  return join('; ', $parts);
1215}
1216
1217
1218function rcmail_draftinfo_decode($str)
1219{
1220  $info = array();
1221  foreach (preg_split('/;\s+/', $str) as $part) {
1222    list($key, $val) = explode('=', $part, 2);
1223    if ($key == 'folder')
1224      $val = base64_decode($val);
1225    $info[$key] = $val;
1226  }
1227
1228  return $info;
1229}
1230
1231
1232function rcmail_message_part_controls()
1233  {
1234  global $MESSAGE;
1235
1236  $part = asciiwords(get_input_value('_part', RCUBE_INPUT_GPC));
1237  if (!is_object($MESSAGE) || !is_array($MESSAGE->parts) || !($_GET['_uid'] && $_GET['_part']) || !$MESSAGE->mime_parts[$part])
1238    return '';
1239
1240  $part = $MESSAGE->mime_parts[$part];
1241  $table = new html_table(array('cols' => 3));
1242
1243  if (!empty($part->filename)) {
1244    $table->add('title', Q(rcube_label('filename')));
1245    $table->add(null, Q($part->filename));
1246    $table->add(null, '[' . html::a('?'.str_replace('_frame=', '_download=', $_SERVER['QUERY_STRING']), Q(rcube_label('download'))) . ']');
1247  }
1248
1249  if (!empty($part->size)) {
1250    $table->add('title', Q(rcube_label('filesize')));
1251    $table->add(null, Q(show_bytes($part->size)));
1252  }
1253
1254  return $table->show($attrib);
1255  }
1256
1257
1258
1259function rcmail_message_part_frame($attrib)
1260  {
1261  global $MESSAGE;
1262
1263  $part = $MESSAGE->mime_parts[asciiwords(get_input_value('_part', RCUBE_INPUT_GPC))];
1264  $ctype_primary = strtolower($part->ctype_primary);
1265
1266  $attrib['src'] = './?' . str_replace('_frame=', ($ctype_primary=='text' ? '_show=' : '_preload='), $_SERVER['QUERY_STRING']);
1267
1268  return html::iframe($attrib);
1269  }
1270
1271
1272/**
1273 * clear message composing settings
1274 */
1275function rcmail_compose_cleanup()
1276  {
1277  if (!isset($_SESSION['compose']))
1278    return;
1279
1280  $rcmail = rcmail::get_instance();
1281  $rcmail->plugins->exec_hook('cleanup_attachments',array());
1282  $rcmail->session->remove('compose');
1283  }
1284
1285
1286/**
1287 * Send the given message using the configured method
1288 *
1289 * @param object $message    Reference to Mail_MIME object
1290 * @param string $from       Sender address string
1291 * @param array  $mailto     Array of recipient address strings
1292 * @param array  $smtp_error SMTP error array (reference)
1293 * @param string $body_file  Location of file with saved message body (reference)
1294 *
1295 * @return boolean Send status.
1296 */
1297function rcmail_deliver_message(&$message, $from, $mailto, &$smtp_error, &$body_file)
1298{
1299  global $CONFIG, $RCMAIL;
1300
1301  $headers = $message->headers();
1302
1303  // send thru SMTP server using custom SMTP library
1304  if ($CONFIG['smtp_server']) {
1305    // generate list of recipients
1306    $a_recipients = array($mailto);
1307
1308    if (strlen($headers['Cc']))
1309      $a_recipients[] = $headers['Cc'];
1310    if (strlen($headers['Bcc']))
1311      $a_recipients[] = $headers['Bcc'];
1312
1313    // clean Bcc from header for recipients
1314    $send_headers = $headers;
1315    unset($send_headers['Bcc']);
1316    // here too, it because txtHeaders() below use $message->_headers not only $send_headers
1317    unset($message->_headers['Bcc']);
1318
1319    $smtp_headers = $message->txtHeaders($send_headers, true);
1320
1321    if ($message->getParam('delay_file_io')) {
1322      // use common temp dir
1323      $temp_dir = $RCMAIL->config->get('temp_dir');
1324      $body_file = tempnam($temp_dir, 'rcmMsg');
1325      if (PEAR::isError($mime_result = $message->saveMessageBody($body_file))) {
1326        raise_error(array('code' => 600, 'type' => 'php',
1327            'file' => __FILE__, 'line' => __LINE__,
1328            'message' => "Could not create message: ".$mime_result->getMessage()),
1329            TRUE, FALSE);
1330        return false;
1331      }
1332      $msg_body = fopen($body_file, 'r');
1333    } else {
1334      $msg_body = $message->get();
1335    }
1336
1337    // send message
1338    if (!is_object($RCMAIL->smtp))
1339      $RCMAIL->smtp_init(true);
1340
1341    $sent = $RCMAIL->smtp->send_mail($from, $a_recipients, $smtp_headers, $msg_body);
1342    $smtp_response = $RCMAIL->smtp->get_response();
1343    $smtp_error = $RCMAIL->smtp->get_error();
1344
1345    if (is_resource($msg_body)) {
1346      fclose($msg_body);
1347    }
1348
1349    // log error
1350    if (!$sent)
1351      raise_error(array('code' => 800, 'type' => 'smtp', 'line' => __LINE__, 'file' => __FILE__,
1352                        'message' => "SMTP error: ".join("\n", $smtp_response)), TRUE, FALSE);
1353  }
1354  // send mail using PHP's mail() function
1355  else {
1356    // unset some headers because they will be added by the mail() function
1357    $headers_enc = $message->headers($headers);
1358    $headers_php = $message->_headers;
1359    unset($headers_php['To'], $headers_php['Subject']);
1360
1361    // reset stored headers and overwrite
1362    $message->_headers = array();
1363    $header_str = $message->txtHeaders($headers_php);
1364
1365    // #1485779
1366    if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
1367      if (preg_match_all('/<([^@]+@[^>]+)>/', $headers_enc['To'], $m)) {
1368        $headers_enc['To'] = implode(', ', $m[1]);
1369        }
1370      }
1371
1372    $msg_body = $message->get();
1373
1374    if (PEAR::isError($msg_body))
1375      raise_error(array('code' => 600, 'type' => 'php',
1376            'file' => __FILE__, 'line' => __LINE__,
1377            'message' => "Could not create message: ".$msg_body->getMessage()),
1378            TRUE, FALSE);
1379    else if (ini_get('safe_mode'))
1380      $sent = mail($headers_enc['To'], $headers_enc['Subject'], $msg_body, $header_str);
1381    else
1382      $sent = mail($headers_enc['To'], $headers_enc['Subject'], $msg_body, $header_str, "-f$from");
1383  }
1384
1385  if ($sent) {
1386    $RCMAIL->plugins->exec_hook('message_sent', array('headers' => $headers, 'body' => $msg_body));
1387
1388    // remove MDN headers after sending
1389    unset($headers['Return-Receipt-To'], $headers['Disposition-Notification-To']);
1390
1391    if ($CONFIG['smtp_log']) {
1392      write_log('sendmail', sprintf("User %s [%s]; Message for %s; %s",
1393        $RCMAIL->user->get_username(),
1394        $_SERVER['REMOTE_ADDR'],
1395        $mailto,
1396        !empty($smtp_response) ? join('; ', $smtp_response) : ''));
1397    }
1398  }
1399
1400  $message->_headers = array();
1401  $message->headers($headers);
1402
1403  return $sent;
1404}
1405
1406
1407function rcmail_send_mdn($uid, &$smtp_error)
1408{
1409  global $RCMAIL, $IMAP;
1410
1411  $message = new rcube_message($uid);
1412
1413  if ($message->headers->mdn_to && !$message->headers->mdn_sent &&
1414    ($IMAP->check_permflag('MDNSENT') || $IMAP->check_permflag('*')))
1415  {
1416    $identity = $RCMAIL->user->get_identity();
1417    $sender = format_email_recipient($identity['email'], $identity['name']);
1418    $recipient = array_shift($IMAP->decode_address_list($message->headers->mdn_to));
1419    $mailto = $recipient['mailto'];
1420
1421    $compose = new Mail_mime($RCMAIL->config->header_delimiter());
1422
1423    $compose->setParam('text_encoding', 'quoted-printable');
1424    $compose->setParam('html_encoding', 'quoted-printable');
1425    $compose->setParam('head_encoding', 'quoted-printable');
1426    $compose->setParam('head_charset', RCMAIL_CHARSET);
1427    $compose->setParam('html_charset', RCMAIL_CHARSET);
1428    $compose->setParam('text_charset', RCMAIL_CHARSET);
1429
1430    // compose headers array
1431    $headers = array(
1432      'Date' => date('r'),
1433      'From' => $sender,
1434      'To'   => $message->headers->mdn_to,
1435      'Subject' => rcube_label('receiptread') . ': ' . $message->subject,
1436      'Message-ID' => sprintf('<%s@%s>', md5(uniqid('rcmail'.mt_rand(),true)), $RCMAIL->config->mail_domain($_SESSION['imap_host'])),
1437      'X-Sender' => $identity['email'],
1438      'References' => trim($message->headers->references . ' ' . $message->headers->messageID),
1439    );
1440
1441    if ($agent = $RCMAIL->config->get('useragent'))
1442      $headers['User-Agent'] = $agent;
1443
1444    $body = rcube_label("yourmessage") . "\r\n\r\n" .
1445      "\t" . rcube_label("to") . ': ' . rcube_imap::decode_mime_string($message->headers->to, $message->headers->charset) . "\r\n" .
1446      "\t" . rcube_label("subject") . ': ' . $message->subject . "\r\n" .
1447      "\t" . rcube_label("sent") . ': ' . format_date($message->headers->date, $RCMAIL->config->get('date_long')) . "\r\n" .
1448      "\r\n" . rcube_label("receiptnote") . "\r\n";
1449
1450    $ua = $RCMAIL->config->get('useragent', "RoundCube Webmail (Version ".RCMAIL_VERSION.")");
1451    $report = "Reporting-UA: $ua\r\n";
1452
1453    if ($message->headers->to)
1454        $report .= "Original-Recipient: {$message->headers->to}\r\n";
1455
1456    $report .= "Final-Recipient: rfc822; {$identity['email']}\r\n" .
1457               "Original-Message-ID: {$message->headers->messageID}\r\n" .
1458               "Disposition: manual-action/MDN-sent-manually; displayed\r\n";
1459
1460    $compose->headers($headers);
1461    $compose->setContentType('multipart/report', array('report-type'=> 'disposition-notification'));
1462    $compose->setTXTBody(rc_wordwrap($body, 75, "\r\n"));
1463    $compose->addAttachment($report, 'message/disposition-notification', 'MDNPart2.txt', false, '7bit', 'inline');
1464
1465    $sent = rcmail_deliver_message($compose, $identity['email'], $mailto, $smtp_error, $body_file);
1466
1467    if ($sent)
1468    {
1469      $IMAP->set_flag($message->uid, 'MDNSENT');
1470      return true;
1471    }
1472  }
1473
1474  return false;
1475}
1476
1477function rcmail_search_filter($attrib)
1478{
1479  global $OUTPUT, $CONFIG;
1480
1481  if (!strlen($attrib['id']))
1482    $attrib['id'] = 'rcmlistfilter';
1483
1484  $attrib['onchange'] = JS_OBJECT_NAME.'.filter_mailbox(this.value)';
1485
1486  /*
1487    RFC3501 (6.4.4): 'ALL', 'RECENT',
1488    'ANSWERED', 'DELETED', 'FLAGGED', 'SEEN',
1489    'UNANSWERED', 'UNDELETED', 'UNFLAGGED', 'UNSEEN',
1490    'NEW', // = (RECENT UNSEEN)
1491    'OLD' // = NOT RECENT
1492  */
1493
1494  $select_filter = new html_select($attrib);
1495  $select_filter->add(rcube_label('all'), 'ALL');
1496  $select_filter->add(rcube_label('unread'), 'UNSEEN');
1497  $select_filter->add(rcube_label('flagged'), 'FLAGGED');
1498  $select_filter->add(rcube_label('unanswered'), 'UNANSWERED');
1499  if (!$CONFIG['skip_deleted'])
1500    $select_filter->add(rcube_label('deleted'), 'DELETED');
1501
1502  $out = $select_filter->show($_SESSION['search_filter']);
1503
1504  $OUTPUT->add_gui_object('search_filter', $attrib['id']);
1505
1506  return $out;
1507}
1508
1509
1510// register UI objects
1511$OUTPUT->add_handlers(array(
1512  'mailboxlist' => 'rcmail_mailbox_list',
1513  'messages' => 'rcmail_message_list',
1514  'messagecountdisplay' => 'rcmail_messagecount_display',
1515  'quotadisplay' => 'rcmail_quota_display',
1516  'mailboxname' => 'rcmail_mailbox_name_display',
1517  'messageheaders' => 'rcmail_message_headers',
1518  'messagebody' => 'rcmail_message_body',
1519  'messagecontentframe' => 'rcmail_messagecontent_frame',
1520  'messagepartframe' => 'rcmail_message_part_frame',
1521  'messagepartcontrols' => 'rcmail_message_part_controls',
1522  'searchfilter' => 'rcmail_search_filter',
1523  'searchform' => array($OUTPUT, 'search_form'),
1524));
1525
1526?>
Note: See TracBrowser for help on using the repository browser.