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

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