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

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