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

Last change on this file since 3627 was 3627, checked in by alec, 3 years ago
  • Some files from /bin + spellchecking actions moved to the new 'utils' task
  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 47.5 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        $body = rcmail_print_body($part, array('safe' => $safe_mode, 'plain' => !$CONFIG['prefer_html']));
937
938        if ($part->ctype_secondary == 'html')
939          $out .= html::div('message-htmlpart', rcmail_html4inline($body, $attrib['id'], 'div.rcmBody'));
940        else
941          $out .= html::div('message-part', $body);
942        }
943      }
944    }
945  else
946    $out .= html::div('message-part', html::tag('pre', array(),
947      rcmail_plain_body(Q($MESSAGE->body, 'strict', false))));
948
949  $ctype_primary = strtolower($MESSAGE->structure->ctype_primary);
950  $ctype_secondary = strtolower($MESSAGE->structure->ctype_secondary);
951
952  // list images after mail body
953  if ($CONFIG['inline_images']
954      && $ctype_primary == 'multipart'
955      && !empty($MESSAGE->attachments)
956      && !strstr($message_body, '<html'))
957    {
958    foreach ($MESSAGE->attachments as $attach_prop) {
959      if (strpos($attach_prop->mimetype, 'image/') === 0) {
960        $out .= html::tag('hr') . html::p(array('align' => "center"),
961          html::img(array(
962            'src' => $MESSAGE->get_part_url($attach_prop->mime_id),
963            'title' => $attach_prop->filename,
964            'alt' => $attach_prop->filename,
965          )));
966        }
967    }
968  }
969
970  // tell client that there are blocked remote objects
971  if ($REMOTE_OBJECTS && !$safe_mode)
972    $OUTPUT->set_env('blockedobjects', true);
973
974  return html::div($attrib, $out);
975  }
976
977
978/**
979 * Convert all relative URLs according to a <base> in HTML
980 */
981function rcmail_resolve_base($body)
982{
983  // check for <base href=...>
984  if (preg_match('!(<base.*href=["\']?)([hftps]{3,5}://[a-z0-9/.%-]+)!i', $body, $regs)) {
985    $replacer = new rcube_base_replacer($regs[2]);
986
987    // replace all relative paths
988    $body = preg_replace_callback('/(src|background|href)=(["\']?)([\.\/]+[^"\'\s]+)(\2|\s|>)/Ui', array($replacer, 'callback'), $body);
989    $body = preg_replace_callback('/(url\s*\()(["\']?)([\.\/]+[^"\'\)\s]+)(\2)\)/Ui', array($replacer, 'callback'), $body);
990  }
991
992  return $body;
993}
994
995/**
996 * modify a HTML message that it can be displayed inside a HTML page
997 */
998function rcmail_html4inline($body, $container_id, $body_id='')
999  {
1000  $last_style_pos = 0;
1001  $body_lc = strtolower($body);
1002
1003  // find STYLE tags
1004  while (($pos = strpos($body_lc, '<style', $last_style_pos)) && ($pos2 = strpos($body_lc, '</style>', $pos)))
1005    {
1006    $pos = strpos($body_lc, '>', $pos)+1;
1007
1008    // replace all css definitions with #container [def]
1009    $styles = rcmail_mod_css_styles(substr($body, $pos, $pos2-$pos), $container_id.($body_id ? ' '.$body_id : ''));
1010
1011    $body = substr($body, 0, $pos) . $styles . substr($body, $pos2);
1012    $body_lc = strtolower($body);
1013    $last_style_pos = $pos2;
1014    }
1015
1016  // modify HTML links to open a new window if clicked
1017  $GLOBALS['rcmail_html_container_id'] = $container_id;
1018  $body = preg_replace_callback('/<(a|link)\s+([^>]+)>/Ui', 'rcmail_alter_html_link', $body);
1019  unset($GLOBALS['rcmail_html_container_id']);
1020
1021  $out = preg_replace(array(
1022      // add comments arround html and other tags
1023      '/(<!DOCTYPE[^>]*>)/i',
1024      '/(<\?xml[^>]*>)/i',
1025      '/(<\/?html[^>]*>)/i',
1026      '/(<\/?head[^>]*>)/i',
1027      '/(<title[^>]*>.*<\/title>)/Ui',
1028      '/(<\/?meta[^>]*>)/i',
1029      // quote <? of php and xml files that are specified as text/html
1030      '/<\?/',
1031      '/\?>/',
1032      // replace <body> with <div>
1033      '/<body([^>]*)>/i',
1034      '/<\/body>/i',
1035      ),
1036    array(
1037      '<!--\\1-->',
1038      '<!--\\1-->',
1039      '<!--\\1-->',
1040      '<!--\\1-->',
1041      '<!--\\1-->',
1042      '<!--\\1-->',
1043      '&lt;?',
1044      '?&gt;',
1045      '<div class="rcmBody"\\1>',
1046      '</div>',
1047      ),
1048    $body);
1049
1050  // make sure there's 'rcmBody' div, we need it for proper css modification
1051  // its name is hardcoded in rcmail_message_body() also
1052  if (!preg_match('/<div class="rcmBody"/', $out))
1053    $out = '<div class="rcmBody">' . $out . '</div>';
1054
1055  return $out;
1056  }
1057
1058
1059/**
1060 * parse link attributes and set correct target
1061 */
1062function rcmail_alter_html_link($matches)
1063{
1064  global $EMAIL_ADDRESS_PATTERN;
1065
1066  $tag = $matches[1];
1067  $attrib = parse_attrib_string($matches[2]);
1068  $end = '>';
1069
1070  if ($tag == 'link' && preg_match('/^https?:\/\//i', $attrib['href'])) {
1071    $attrib['href'] = "?_task=utils&amp;_action=modcss&amp;u=" . urlencode($attrib['href'])
1072        . "&amp;c=" . urlencode($GLOBALS['rcmail_html_container_id']);
1073    $end = ' />';
1074  }
1075  else if (preg_match('/^mailto:'.$EMAIL_ADDRESS_PATTERN.'(\?[^"\'>]+)?/i', $attrib['href'], $mailto)) {
1076    $attrib['href'] = $mailto[0];
1077    $attrib['onclick'] = sprintf(
1078      "return %s.command('compose','%s',this)",
1079      JS_OBJECT_NAME,
1080      JQ($mailto[1].$mailto[2]));
1081  }
1082  else if (!empty($attrib['href']) && $attrib['href'][0] != '#') {
1083    $attrib['target'] = '_blank';
1084  }
1085
1086  return "<$tag" . html::attrib_string($attrib, array('href','name','target','onclick','id','class','style','title','rel','type','media')) . $end;
1087}
1088
1089
1090/**
1091 * decode address string and re-format it as HTML links
1092 */
1093function rcmail_address_string($input, $max=null, $linked=false, $addicon=null)
1094{
1095  global $IMAP, $RCMAIL, $PRINT_MODE, $CONFIG, $OUTPUT, $EMAIL_ADDRESS_PATTERN;
1096  static $got_writable_abook = null;
1097
1098  $a_parts = $IMAP->decode_address_list($input);
1099
1100  if (!sizeof($a_parts))
1101    return $input;
1102
1103  $c = count($a_parts);
1104  $j = 0;
1105  $out = '';
1106
1107  if ($got_writable_abook === null && $books = $RCMAIL->get_address_sources(true)) {
1108    $got_writable_abook = true;
1109  }
1110
1111  foreach ($a_parts as $part) {
1112    $j++;
1113    if ($PRINT_MODE) {
1114      $out .= sprintf('%s &lt;%s&gt;', Q($part['name']), $part['mailto']);
1115    }
1116    else if (check_email($part['mailto'], false)) {
1117      if ($linked) {
1118        $out .= html::a(array(
1119            'href' => 'mailto:'.$part['mailto'],
1120            'onclick' => sprintf("return %s.command('compose','%s',this)", JS_OBJECT_NAME, JQ($part['mailto'])),
1121            'title' => $part['mailto'],
1122            'class' => "rcmContactAddress",
1123          ),
1124        Q($part['name']));
1125      }
1126      else {
1127        $out .= html::span(array('title' => $part['mailto'], 'class' => "rcmContactAddress"), Q($part['name']));
1128      }
1129
1130      if ($addicon && $got_writable_abook) {
1131        $out .= '&nbsp;' . html::a(array(
1132            'href' => "#add",
1133            'onclick' => sprintf("return %s.command('add-contact','%s',this)", JS_OBJECT_NAME, urlencode($part['string'])),
1134            'title' => rcube_label('addtoaddressbook'),
1135          ),
1136          html::img(array(
1137            'src' => $CONFIG['skin_path'] . $addicon,
1138            'alt' => "Add contact",
1139          )));
1140      }
1141    }
1142    else {
1143      if ($part['name'])
1144        $out .= Q($part['name']);
1145      if ($part['mailto'])
1146        $out .= (strlen($out) ? ' ' : '') . sprintf('&lt;%s&gt;', Q($part['mailto']));
1147    }
1148
1149    if ($c>$j)
1150      $out .= ','.($max ? '&nbsp;' : ' ');
1151
1152    if ($max && $j==$max && $c>$j) {
1153      $out .= '...';
1154      break;
1155    }
1156  }
1157
1158  return $out;
1159}
1160
1161
1162/**
1163 * Wrap text to a given number of characters per line
1164 * but respect the mail quotation of replies messages (>)
1165 *
1166 * @param string Text to wrap
1167 * @param int The line width
1168 * @return string The wrapped text
1169 */
1170function rcmail_wrap_quoted($text, $max = 76)
1171{
1172  // Rebuild the message body with a maximum of $max chars, while keeping quoted message.
1173  $lines = preg_split('/\r?\n/', trim($text));
1174  $out = '';
1175
1176  foreach ($lines as $line) {
1177    if (strlen($line) > $max) {
1178      if (preg_match('/^([>\s]+)/', $line, $regs)) {
1179        $length = strlen($regs[0]);
1180        $prefix = substr($line, 0, $length);
1181
1182        // Remove '> ' from the line, then wordwrap() the line
1183        $line = rc_wordwrap(substr($line, $length), $max - $length);
1184
1185        // Rebuild the line with '> ' at the beginning of each 'subline'
1186        $newline = '';
1187        foreach (explode("\n", $line) as $l) {
1188          $newline .= $prefix . $l . "\n";
1189        }
1190
1191        // Remove the righest newline char
1192        $line = rtrim($newline);
1193      }
1194      else {
1195        $line = rc_wordwrap($line, $max);
1196      }
1197    }
1198
1199    // Append the line
1200    $out .= $line . "\n";
1201  }
1202
1203  return $out;
1204}
1205
1206
1207function rcmail_draftinfo_encode($p)
1208{
1209  $parts = array();
1210  foreach ($p as $key => $val)
1211    $parts[] = $key . '=' . ($key == 'folder' ? base64_encode($val) : $val);
1212
1213  return join('; ', $parts);
1214}
1215
1216
1217function rcmail_draftinfo_decode($str)
1218{
1219  $info = array();
1220  foreach (preg_split('/;\s+/', $str) as $part) {
1221    list($key, $val) = explode('=', $part, 2);
1222    if ($key == 'folder')
1223      $val = base64_decode($val);
1224    $info[$key] = $val;
1225  }
1226
1227  return $info;
1228}
1229
1230
1231function rcmail_message_part_controls()
1232  {
1233  global $MESSAGE;
1234
1235  $part = asciiwords(get_input_value('_part', RCUBE_INPUT_GPC));
1236  if (!is_object($MESSAGE) || !is_array($MESSAGE->parts) || !($_GET['_uid'] && $_GET['_part']) || !$MESSAGE->mime_parts[$part])
1237    return '';
1238
1239  $part = $MESSAGE->mime_parts[$part];
1240  $table = new html_table(array('cols' => 3));
1241
1242  if (!empty($part->filename)) {
1243    $table->add('title', Q(rcube_label('filename')));
1244    $table->add(null, Q($part->filename));
1245    $table->add(null, '[' . html::a('?'.str_replace('_frame=', '_download=', $_SERVER['QUERY_STRING']), Q(rcube_label('download'))) . ']');
1246  }
1247
1248  if (!empty($part->size)) {
1249    $table->add('title', Q(rcube_label('filesize')));
1250    $table->add(null, Q(show_bytes($part->size)));
1251  }
1252
1253  return $table->show($attrib);
1254  }
1255
1256
1257
1258function rcmail_message_part_frame($attrib)
1259  {
1260  global $MESSAGE;
1261
1262  $part = $MESSAGE->mime_parts[asciiwords(get_input_value('_part', RCUBE_INPUT_GPC))];
1263  $ctype_primary = strtolower($part->ctype_primary);
1264
1265  $attrib['src'] = './?' . str_replace('_frame=', ($ctype_primary=='text' ? '_show=' : '_preload='), $_SERVER['QUERY_STRING']);
1266
1267  return html::iframe($attrib);
1268  }
1269
1270
1271/**
1272 * clear message composing settings
1273 */
1274function rcmail_compose_cleanup()
1275  {
1276  if (!isset($_SESSION['compose']))
1277    return;
1278
1279  $rcmail = rcmail::get_instance();
1280  $rcmail->plugins->exec_hook('cleanup_attachments',array());
1281  $rcmail->session->remove('compose');
1282  }
1283
1284
1285/**
1286 * Send the given message using the configured method
1287 *
1288 * @param object $message    Reference to Mail_MIME object
1289 * @param string $from       Sender address string
1290 * @param array  $mailto     Array of recipient address strings
1291 * @param array  $smtp_error SMTP error array (reference)
1292 * @param string $body_file  Location of file with saved message body (reference)
1293 *
1294 * @return boolean Send status.
1295 */
1296function rcmail_deliver_message(&$message, $from, $mailto, &$smtp_error, &$body_file)
1297{
1298  global $CONFIG, $RCMAIL;
1299
1300  $headers = $message->headers();
1301
1302  // send thru SMTP server using custom SMTP library
1303  if ($CONFIG['smtp_server']) {
1304    // generate list of recipients
1305    $a_recipients = array($mailto);
1306
1307    if (strlen($headers['Cc']))
1308      $a_recipients[] = $headers['Cc'];
1309    if (strlen($headers['Bcc']))
1310      $a_recipients[] = $headers['Bcc'];
1311
1312    // clean Bcc from header for recipients
1313    $send_headers = $headers;
1314    unset($send_headers['Bcc']);
1315    // here too, it because txtHeaders() below use $message->_headers not only $send_headers
1316    unset($message->_headers['Bcc']);
1317
1318    $smtp_headers = $message->txtHeaders($send_headers, true);
1319
1320    if ($message->getParam('delay_file_io')) {
1321      // use common temp dir
1322      $temp_dir = $RCMAIL->config->get('temp_dir');
1323      $body_file = tempnam($temp_dir, 'rcmMsg');
1324      if (PEAR::isError($mime_result = $message->saveMessageBody($body_file))) {
1325        raise_error(array('code' => 600, 'type' => 'php',
1326            'file' => __FILE__, 'line' => __LINE__,
1327            'message' => "Could not create message: ".$mime_result->getMessage()),
1328            TRUE, FALSE);
1329        return false;
1330      }
1331      $msg_body = fopen($body_file, 'r');
1332    } else {
1333      $msg_body = $message->get();
1334    }
1335
1336    // send message
1337    if (!is_object($RCMAIL->smtp))
1338      $RCMAIL->smtp_init(true);
1339
1340    $sent = $RCMAIL->smtp->send_mail($from, $a_recipients, $smtp_headers, $msg_body);
1341    $smtp_response = $RCMAIL->smtp->get_response();
1342    $smtp_error = $RCMAIL->smtp->get_error();
1343
1344    if (is_resource($msg_body)) {
1345      fclose($msg_body);
1346    }
1347
1348    // log error
1349    if (!$sent)
1350      raise_error(array('code' => 800, 'type' => 'smtp', 'line' => __LINE__, 'file' => __FILE__,
1351                        'message' => "SMTP error: ".join("\n", $smtp_response)), TRUE, FALSE);
1352  }
1353  // send mail using PHP's mail() function
1354  else {
1355    // unset some headers because they will be added by the mail() function
1356    $headers_enc = $message->headers($headers);
1357    $headers_php = $message->_headers;
1358    unset($headers_php['To'], $headers_php['Subject']);
1359
1360    // reset stored headers and overwrite
1361    $message->_headers = array();
1362    $header_str = $message->txtHeaders($headers_php);
1363
1364    // #1485779
1365    if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
1366      if (preg_match_all('/<([^@]+@[^>]+)>/', $headers_enc['To'], $m)) {
1367        $headers_enc['To'] = implode(', ', $m[1]);
1368        }
1369      }
1370
1371    $msg_body = $message->get();
1372
1373    if (PEAR::isError($msg_body))
1374      raise_error(array('code' => 600, 'type' => 'php',
1375            'file' => __FILE__, 'line' => __LINE__,
1376            'message' => "Could not create message: ".$msg_body->getMessage()),
1377            TRUE, FALSE);
1378    else if (ini_get('safe_mode'))
1379      $sent = mail($headers_enc['To'], $headers_enc['Subject'], $msg_body, $header_str);
1380    else
1381      $sent = mail($headers_enc['To'], $headers_enc['Subject'], $msg_body, $header_str, "-f$from");
1382  }
1383
1384  if ($sent) {
1385    $RCMAIL->plugins->exec_hook('message_sent', array('headers' => $headers, 'body' => $msg_body));
1386
1387    // remove MDN headers after sending
1388    unset($headers['Return-Receipt-To'], $headers['Disposition-Notification-To']);
1389
1390    if ($CONFIG['smtp_log']) {
1391      write_log('sendmail', sprintf("User %s [%s]; Message for %s; %s",
1392        $RCMAIL->user->get_username(),
1393        $_SERVER['REMOTE_ADDR'],
1394        $mailto,
1395        !empty($smtp_response) ? join('; ', $smtp_response) : ''));
1396    }
1397  }
1398
1399  $message->_headers = array();
1400  $message->headers($headers);
1401
1402  return $sent;
1403}
1404
1405
1406function rcmail_send_mdn($uid, &$smtp_error)
1407{
1408  global $RCMAIL, $IMAP;
1409
1410  $message = new rcube_message($uid);
1411
1412  if ($message->headers->mdn_to && !$message->headers->mdn_sent &&
1413    ($IMAP->check_permflag('MDNSENT') || $IMAP->check_permflag('*')))
1414  {
1415    $identity = $RCMAIL->user->get_identity();
1416    $sender = format_email_recipient($identity['email'], $identity['name']);
1417    $recipient = array_shift($IMAP->decode_address_list($message->headers->mdn_to));
1418    $mailto = $recipient['mailto'];
1419
1420    $compose = new Mail_mime($RCMAIL->config->header_delimiter());
1421
1422    $compose->setParam('text_encoding', 'quoted-printable');
1423    $compose->setParam('html_encoding', 'quoted-printable');
1424    $compose->setParam('head_encoding', 'quoted-printable');
1425    $compose->setParam('head_charset', RCMAIL_CHARSET);
1426    $compose->setParam('html_charset', RCMAIL_CHARSET);
1427    $compose->setParam('text_charset', RCMAIL_CHARSET);
1428
1429    // compose headers array
1430    $headers = array(
1431      'Date' => date('r'),
1432      'From' => $sender,
1433      'To'   => $message->headers->mdn_to,
1434      'Subject' => rcube_label('receiptread') . ': ' . $message->subject,
1435      'Message-ID' => sprintf('<%s@%s>', md5(uniqid('rcmail'.mt_rand(),true)), $RCMAIL->config->mail_domain($_SESSION['imap_host'])),
1436      'X-Sender' => $identity['email'],
1437      'References' => trim($message->headers->references . ' ' . $message->headers->messageID),
1438    );
1439
1440    if ($agent = $RCMAIL->config->get('useragent'))
1441      $headers['User-Agent'] = $agent;
1442
1443    $body = rcube_label("yourmessage") . "\r\n\r\n" .
1444      "\t" . rcube_label("to") . ': ' . rcube_imap::decode_mime_string($message->headers->to, $message->headers->charset) . "\r\n" .
1445      "\t" . rcube_label("subject") . ': ' . $message->subject . "\r\n" .
1446      "\t" . rcube_label("sent") . ': ' . format_date($message->headers->date, $RCMAIL->config->get('date_long')) . "\r\n" .
1447      "\r\n" . rcube_label("receiptnote") . "\r\n";
1448
1449    $ua = $RCMAIL->config->get('useragent', "RoundCube Webmail (Version ".RCMAIL_VERSION.")");
1450    $report = "Reporting-UA: $ua\r\n";
1451
1452    if ($message->headers->to)
1453        $report .= "Original-Recipient: {$message->headers->to}\r\n";
1454
1455    $report .= "Final-Recipient: rfc822; {$identity['email']}\r\n" .
1456               "Original-Message-ID: {$message->headers->messageID}\r\n" .
1457               "Disposition: manual-action/MDN-sent-manually; displayed\r\n";
1458
1459    $compose->headers($headers);
1460    $compose->setContentType('multipart/report', array('report-type'=> 'disposition-notification'));
1461    $compose->setTXTBody(rc_wordwrap($body, 75, "\r\n"));
1462    $compose->addAttachment($report, 'message/disposition-notification', 'MDNPart2.txt', false, '7bit', 'inline');
1463
1464    $sent = rcmail_deliver_message($compose, $identity['email'], $mailto, $smtp_error, $body_file);
1465
1466    if ($sent)
1467    {
1468      $IMAP->set_flag($message->uid, 'MDNSENT');
1469      return true;
1470    }
1471  }
1472
1473  return false;
1474}
1475
1476function rcmail_search_filter($attrib)
1477{
1478  global $OUTPUT, $CONFIG;
1479
1480  if (!strlen($attrib['id']))
1481    $attrib['id'] = 'rcmlistfilter';
1482
1483  $attrib['onchange'] = JS_OBJECT_NAME.'.filter_mailbox(this.value)';
1484
1485  /*
1486    RFC3501 (6.4.4): 'ALL', 'RECENT',
1487    'ANSWERED', 'DELETED', 'FLAGGED', 'SEEN',
1488    'UNANSWERED', 'UNDELETED', 'UNFLAGGED', 'UNSEEN',
1489    'NEW', // = (RECENT UNSEEN)
1490    'OLD' // = NOT RECENT
1491  */
1492
1493  $select_filter = new html_select($attrib);
1494  $select_filter->add(rcube_label('all'), 'ALL');
1495  $select_filter->add(rcube_label('unread'), 'UNSEEN');
1496  $select_filter->add(rcube_label('flagged'), 'FLAGGED');
1497  $select_filter->add(rcube_label('unanswered'), 'UNANSWERED');
1498  if (!$CONFIG['skip_deleted'])
1499    $select_filter->add(rcube_label('deleted'), 'DELETED');
1500
1501  $out = $select_filter->show($_SESSION['search_filter']);
1502
1503  $OUTPUT->add_gui_object('search_filter', $attrib['id']);
1504
1505  return $out;
1506}
1507
1508
1509// register UI objects
1510$OUTPUT->add_handlers(array(
1511  'mailboxlist' => 'rcmail_mailbox_list',
1512  'messages' => 'rcmail_message_list',
1513  'messagecountdisplay' => 'rcmail_messagecount_display',
1514  'quotadisplay' => 'rcmail_quota_display',
1515  'mailboxname' => 'rcmail_mailbox_name_display',
1516  'messageheaders' => 'rcmail_message_headers',
1517  'messagebody' => 'rcmail_message_body',
1518  'messagecontentframe' => 'rcmail_messagecontent_frame',
1519  'messagepartframe' => 'rcmail_message_part_frame',
1520  'messagepartcontrols' => 'rcmail_message_part_controls',
1521  'searchfilter' => 'rcmail_search_filter',
1522  'searchform' => array($OUTPUT, 'search_form'),
1523));
1524
1525?>
1526
Note: See TracBrowser for help on using the repository browser.