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

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