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

Last change on this file since 3385 was 3385, checked in by alec, 3 years ago
  • Implemented messages copying using drag&drop + SHIFT (#1484086)
  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 47.6 KB
Line 
1<?php
2
3/*
4 +-----------------------------------------------------------------------+
5 | program/steps/mail/func.inc                                           |
6 |                                                                       |
7 | This file is part of the RoundCube Webmail client                     |
8 | Copyright (C) 2005-2010, RoundCube Dev. - Switzerland                 |
9 | Licensed under the GNU GPL                                            |
10 |                                                                       |
11 | PURPOSE:                                                              |
12 |   Provide webmail functionality and GUI objects                       |
13 |                                                                       |
14 +-----------------------------------------------------------------------+
15 | Author: Thomas Bruederli <roundcube@gmail.com>                        |
16 +-----------------------------------------------------------------------+
17
18 $Id$
19
20*/
21
22// setup some global vars used by mail steps
23$SENT_MBOX = $RCMAIL->config->get('sent_mbox');
24$DRAFTS_MBOX = $RCMAIL->config->get('drafts_mbox');
25$SEARCH_MODS_DEFAULT = array('*' => array('subject'=>1, 'from'=>1), $SENT_MBOX => array('subject'=>1, 'to'=>1), $DRAFTS_MBOX => array('subject'=>1, 'to'=>1));
26
27$EMAIL_ADDRESS_PATTERN = '([a-z0-9][a-z0-9\-\.\+\_]*@[a-z0-9][a-z0-9\-\.]*\\.[a-z]{2,5})';
28
29// actions that do not require imap connection
30$NOIMAP_ACTIONS = array('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']));
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)
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);
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  // add comments arround html and other tags
1024  $out = preg_replace(array(
1025      '/(<!DOCTYPE[^>]*>)/i',
1026      '/(<\?xml[^>]*>)/i',
1027      '/(<\/?html[^>]*>)/i',
1028      '/(<\/?head[^>]*>)/i',
1029      '/(<title[^>]*>.*<\/title>)/Ui',
1030      '/(<\/?meta[^>]*>)/i'),
1031    '<!--\\1-->',
1032    $body);
1033
1034  $out = preg_replace(
1035    array('/<body([^>]*)>/i', '/<\/body>/i'),
1036    array('<div class="rcmBody"\\1>', '</div>'),
1037    $out);
1038
1039  // quote <? of php and xml files that are specified as text/html
1040  $out = preg_replace(array('/<\?/', '/\?>/'), array('&lt;?', '?&gt;'), $out);
1041
1042  return $out;
1043  }
1044
1045
1046/**
1047 * parse link attributes and set correct target
1048 */
1049function rcmail_alter_html_link($matches)
1050{
1051  global $EMAIL_ADDRESS_PATTERN;
1052 
1053  $tag = $matches[1];
1054  $attrib = parse_attrib_string($matches[2]);
1055  $end = '>';
1056
1057  if ($tag == 'link' && preg_match('/^https?:\/\//i', $attrib['href'])) {
1058    $attrib['href'] = "./bin/modcss.php?u=" . urlencode($attrib['href']) . "&amp;c=" . urlencode($GLOBALS['rcmail_html_container_id']);
1059    $end = ' />';
1060  }
1061  else if (preg_match('/^mailto:'.$EMAIL_ADDRESS_PATTERN.'(\?[^"\'>]+)?/i', $attrib['href'], $mailto)) {
1062    $attrib['href'] = $mailto[0];
1063    $attrib['onclick'] = sprintf(
1064      "return %s.command('compose','%s',this)",
1065      JS_OBJECT_NAME,
1066      JQ($mailto[1].$mailto[2]));
1067  }
1068  else if (!empty($attrib['href']) && $attrib['href'][0] != '#') {
1069    $attrib['target'] = '_blank';
1070  }
1071
1072  return "<$tag" . html::attrib_string($attrib, array('href','name','target','onclick','id','class','style','title','rel','type','media')) . $end;
1073}
1074
1075
1076/**
1077 * decode address string and re-format it as HTML links
1078 */
1079function rcmail_address_string($input, $max=null, $linked=false, $addicon=null)
1080{
1081  global $IMAP, $RCMAIL, $PRINT_MODE, $CONFIG, $OUTPUT, $EMAIL_ADDRESS_PATTERN;
1082  static $got_writable_abook = null;
1083
1084  $a_parts = $IMAP->decode_address_list($input);
1085
1086  if (!sizeof($a_parts))
1087    return $input;
1088
1089  $c = count($a_parts);
1090  $j = 0;
1091  $out = '';
1092
1093  if ($got_writable_abook === null && $books = $RCMAIL->get_address_sources(true)) {
1094    $got_writable_abook = true;
1095  }
1096
1097  foreach ($a_parts as $part) {
1098    $j++;
1099    if ($PRINT_MODE) {
1100      $out .= sprintf('%s &lt;%s&gt;', Q($part['name']), $part['mailto']);
1101    }
1102    else if (check_email($part['mailto'], false)) {
1103      if ($linked) {
1104        $out .= html::a(array(
1105            'href' => 'mailto:'.$part['mailto'],
1106            'onclick' => sprintf("return %s.command('compose','%s',this)", JS_OBJECT_NAME, JQ($part['mailto'])),
1107            'title' => $part['mailto'],
1108            'class' => "rcmContactAddress",
1109          ),
1110        Q($part['name']));
1111      }
1112      else {
1113        $out .= html::span(array('title' => $part['mailto'], 'class' => "rcmContactAddress"), Q($part['name']));
1114      }
1115
1116      if ($addicon && $got_writable_abook) {
1117        $out .= '&nbsp;' . html::a(array(
1118            'href' => "#add",
1119            'onclick' => sprintf("return %s.command('add-contact','%s',this)", JS_OBJECT_NAME, urlencode($part['string'])),
1120            'title' => rcube_label('addtoaddressbook'),
1121          ),
1122          html::img(array(
1123            'src' => $CONFIG['skin_path'] . $addicon,
1124            'alt' => "Add contact",
1125          )));
1126      }
1127    }
1128    else {
1129      if ($part['name'])
1130        $out .= Q($part['name']);
1131      if ($part['mailto'])
1132        $out .= (strlen($out) ? ' ' : '') . sprintf('&lt;%s&gt;', Q($part['mailto']));
1133    }
1134     
1135    if ($c>$j)
1136      $out .= ','.($max ? '&nbsp;' : ' ');
1137       
1138    if ($max && $j==$max && $c>$j) {
1139      $out .= '...';
1140      break;
1141    }
1142  }
1143   
1144  return $out;
1145}
1146
1147
1148/**
1149 * Wrap text to a given number of characters per line
1150 * but respect the mail quotation of replies messages (>)
1151 *
1152 * @param string Text to wrap
1153 * @param int The line width
1154 * @return string The wrapped text
1155 */
1156function rcmail_wrap_quoted($text, $max = 76)
1157{
1158  // Rebuild the message body with a maximum of $max chars, while keeping quoted message.
1159  $lines = preg_split('/\r?\n/', trim($text));
1160  $out = '';
1161
1162  foreach ($lines as $line) {
1163    if (strlen($line) > $max) {
1164      if (preg_match('/^([>\s]+)/', $line, $regs)) {
1165        $length = strlen($regs[0]);
1166        $prefix = substr($line, 0, $length);
1167
1168        // Remove '> ' from the line, then wordwrap() the line
1169        $line = rc_wordwrap(substr($line, $length), $max - $length);
1170
1171        // Rebuild the line with '> ' at the beginning of each 'subline'
1172        $newline = '';
1173        foreach (explode("\n", $line) as $l) {
1174          $newline .= $prefix . $l . "\n";
1175        }
1176
1177        // Remove the righest newline char
1178        $line = rtrim($newline);
1179      }
1180      else {
1181        $line = rc_wordwrap($line, $max);
1182      }
1183    }
1184
1185    // Append the line
1186    $out .= $line . "\n";
1187  }
1188 
1189  return $out;
1190}
1191
1192
1193function rcmail_draftinfo_encode($p)
1194{
1195  $parts = array();
1196  foreach ($p as $key => $val)
1197    $parts[] = $key . '=' . ($key == 'folder' ? base64_encode($val) : $val);
1198 
1199  return join('; ', $parts);
1200}
1201
1202
1203function rcmail_draftinfo_decode($str)
1204{
1205  $info = array();
1206  foreach (preg_split('/;\s+/', $str) as $part) {
1207    list($key, $val) = explode('=', $part, 2);
1208    if ($key == 'folder')
1209      $val = base64_decode($val);
1210    $info[$key] = $val;
1211  }
1212 
1213  return $info;
1214}
1215
1216
1217function rcmail_message_part_controls()
1218  {
1219  global $MESSAGE;
1220 
1221  $part = asciiwords(get_input_value('_part', RCUBE_INPUT_GPC));
1222  if (!is_object($MESSAGE) || !is_array($MESSAGE->parts) || !($_GET['_uid'] && $_GET['_part']) || !$MESSAGE->mime_parts[$part])
1223    return '';
1224   
1225  $part = $MESSAGE->mime_parts[$part];
1226  $table = new html_table(array('cols' => 3));
1227 
1228  if (!empty($part->filename)) {
1229    $table->add('title', Q(rcube_label('filename')));
1230    $table->add(null, Q($part->filename));
1231    $table->add(null, '[' . html::a('?'.str_replace('_frame=', '_download=', $_SERVER['QUERY_STRING']), Q(rcube_label('download'))) . ']');
1232  }
1233 
1234  if (!empty($part->size)) {
1235    $table->add('title', Q(rcube_label('filesize')));
1236    $table->add(null, Q(show_bytes($part->size)));
1237  }
1238 
1239  return $table->show($attrib);
1240  }
1241
1242
1243
1244function rcmail_message_part_frame($attrib)
1245  {
1246  global $MESSAGE;
1247 
1248  $part = $MESSAGE->mime_parts[asciiwords(get_input_value('_part', RCUBE_INPUT_GPC))];
1249  $ctype_primary = strtolower($part->ctype_primary);
1250
1251  $attrib['src'] = './?' . str_replace('_frame=', ($ctype_primary=='text' ? '_show=' : '_preload='), $_SERVER['QUERY_STRING']);
1252
1253  return html::iframe($attrib);
1254  }
1255
1256
1257/**
1258 * clear message composing settings
1259 */
1260function rcmail_compose_cleanup()
1261  {
1262  if (!isset($_SESSION['compose']))
1263    return;
1264
1265  $rcmail = rcmail::get_instance();
1266  $rcmail->plugins->exec_hook('cleanup_attachments',array());
1267  $rcmail->session->remove('compose');
1268  }
1269 
1270
1271/**
1272 * Send the given message using the configured method
1273 *
1274 * @param object $message    Reference to Mail_MIME object
1275 * @param string $from       Sender address string
1276 * @param array  $mailto     Array of recipient address strings
1277 * @param array  $smtp_error SMTP error array (reference)
1278 * @param string $body_file  Location of file with saved message body (reference)
1279 *
1280 * @return boolean Send status.
1281 */
1282function rcmail_deliver_message(&$message, $from, $mailto, &$smtp_error, &$body_file)
1283{
1284  global $CONFIG, $RCMAIL;
1285
1286  $headers = $message->headers();
1287
1288  // send thru SMTP server using custom SMTP library
1289  if ($CONFIG['smtp_server']) {
1290    // generate list of recipients
1291    $a_recipients = array($mailto);
1292 
1293    if (strlen($headers['Cc']))
1294      $a_recipients[] = $headers['Cc'];
1295    if (strlen($headers['Bcc']))
1296      $a_recipients[] = $headers['Bcc'];
1297 
1298    // clean Bcc from header for recipients
1299    $send_headers = $headers;
1300    unset($send_headers['Bcc']);
1301    // here too, it because txtHeaders() below use $message->_headers not only $send_headers
1302    unset($message->_headers['Bcc']);
1303
1304    $smtp_headers = $message->txtHeaders($send_headers, true);
1305
1306    if ($message->getParam('delay_file_io')) {
1307      // use common temp dir
1308      $temp_dir = $RCMAIL->config->get('temp_dir');
1309      $body_file = tempnam($temp_dir, 'rcmMsg');
1310      if (PEAR::isError($mime_result = $message->saveMessageBody($body_file))) {
1311        raise_error(array('code' => 600, 'type' => 'php',
1312            'file' => __FILE__, 'line' => __LINE__,
1313            'message' => "Could not create message: ".$mime_result->getMessage()),
1314            TRUE, FALSE);
1315        return false;
1316      }
1317      $msg_body = fopen($body_file, 'r');
1318    } else {
1319      $msg_body = $message->get();
1320    }
1321
1322    // send message
1323    if (!is_object($RCMAIL->smtp))
1324      $RCMAIL->smtp_init(true);
1325     
1326    $sent = $RCMAIL->smtp->send_mail($from, $a_recipients, $smtp_headers, $msg_body);
1327    $smtp_response = $RCMAIL->smtp->get_response();
1328    $smtp_error = $RCMAIL->smtp->get_error();
1329
1330    if (is_resource($msg_body)) {
1331      fclose($msg_body);
1332    }
1333
1334    // log error
1335    if (!$sent)
1336      raise_error(array('code' => 800, 'type' => 'smtp', 'line' => __LINE__, 'file' => __FILE__,
1337                        'message' => "SMTP error: ".join("\n", $smtp_response)), TRUE, FALSE);
1338  }
1339  // send mail using PHP's mail() function
1340  else {
1341    // unset some headers because they will be added by the mail() function
1342    $headers_enc = $message->headers($headers);
1343    $headers_php = $message->_headers;
1344    unset($headers_php['To'], $headers_php['Subject']);
1345   
1346    // reset stored headers and overwrite
1347    $message->_headers = array();
1348    $header_str = $message->txtHeaders($headers_php);
1349   
1350    // #1485779
1351    if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
1352      if (preg_match_all('/<([^@]+@[^>]+)>/', $headers_enc['To'], $m)) {
1353        $headers_enc['To'] = implode(', ', $m[1]);
1354        }
1355      }
1356   
1357    $msg_body = $message->get();
1358
1359    if (PEAR::isError($msg_body))
1360      raise_error(array('code' => 600, 'type' => 'php',
1361            'file' => __FILE__, 'line' => __LINE__,
1362            'message' => "Could not create message: ".$msg_body->getMessage()),
1363            TRUE, FALSE);
1364    else if (ini_get('safe_mode'))
1365      $sent = mail($headers_enc['To'], $headers_enc['Subject'], $msg_body, $header_str);
1366    else
1367      $sent = mail($headers_enc['To'], $headers_enc['Subject'], $msg_body, $header_str, "-f$from");
1368  }
1369 
1370  if ($sent) {
1371    $RCMAIL->plugins->exec_hook('message_sent', array('headers' => $headers, 'body' => $msg_body));
1372   
1373    // remove MDN headers after sending
1374    unset($headers['Return-Receipt-To'], $headers['Disposition-Notification-To']);
1375   
1376    if ($CONFIG['smtp_log']) {
1377      write_log('sendmail', sprintf("User %s [%s]; Message for %s; %s",
1378        $RCMAIL->user->get_username(),
1379        $_SERVER['REMOTE_ADDR'],
1380        $mailto,
1381        !empty($smtp_response) ? join('; ', $smtp_response) : ''));
1382    }
1383  }
1384
1385  $message->_headers = array();
1386  $message->headers($headers);
1387 
1388  return $sent;
1389}
1390
1391
1392function rcmail_send_mdn($uid, &$smtp_error)
1393{
1394  global $RCMAIL, $IMAP;
1395
1396  $message = new rcube_message($uid);
1397 
1398  if ($message->headers->mdn_to && !$message->headers->mdn_sent &&
1399    ($IMAP->check_permflag('MDNSENT') || $IMAP->check_permflag('*')))
1400  {
1401    $identity = $RCMAIL->user->get_identity();
1402    $sender = format_email_recipient($identity['email'], $identity['name']);
1403    $recipient = array_shift($IMAP->decode_address_list($message->headers->mdn_to));
1404    $mailto = $recipient['mailto'];
1405
1406    $compose = new Mail_mime($RCMAIL->config->header_delimiter());
1407
1408    $compose->setParam('text_encoding', 'quoted-printable');
1409    $compose->setParam('html_encoding', 'quoted-printable');
1410    $compose->setParam('head_encoding', 'quoted-printable');
1411    $compose->setParam('head_charset', RCMAIL_CHARSET);
1412    $compose->setParam('html_charset', RCMAIL_CHARSET);
1413    $compose->setParam('text_charset', RCMAIL_CHARSET);
1414   
1415    // compose headers array
1416    $headers = array(
1417      'Date' => date('r'),
1418      'From' => $sender,
1419      'To'   => $message->headers->mdn_to,
1420      'Subject' => rcube_label('receiptread') . ': ' . $message->subject,
1421      'Message-ID' => sprintf('<%s@%s>', md5(uniqid('rcmail'.mt_rand(),true)), $RCMAIL->config->mail_domain($_SESSION['imap_host'])),
1422      'X-Sender' => $identity['email'],
1423      'Content-Type' => 'multipart/report; report-type=disposition-notification',
1424    );
1425   
1426    if ($agent = $RCMAIL->config->get('useragent'))
1427      $headers['User-Agent'] = $agent;
1428
1429    $body = rcube_label("yourmessage") . "\r\n\r\n" .
1430      "\t" . rcube_label("to") . ': ' . rcube_imap::decode_mime_string($message->headers->to, $message->headers->charset) . "\r\n" .
1431      "\t" . rcube_label("subject") . ': ' . $message->subject . "\r\n" .
1432      "\t" . rcube_label("sent") . ': ' . format_date($message->headers->date, $RCMAIL->config->get('date_long')) . "\r\n" .
1433      "\r\n" . rcube_label("receiptnote") . "\r\n";
1434   
1435    $ua = $RCMAIL->config->get('useragent', "RoundCube Webmail (Version ".RCMAIL_VERSION.")");
1436    $report = "Reporting-UA: $ua\r\n";
1437   
1438    if ($message->headers->to)
1439        $report .= "Original-Recipient: {$message->headers->to}\r\n";
1440   
1441    $report .= "Final-Recipient: rfc822; {$identity['email']}\r\n" .
1442               "Original-Message-ID: {$message->headers->messageID}\r\n" .
1443               "Disposition: manual-action/MDN-sent-manually; displayed\r\n";
1444   
1445    $compose->headers($headers);
1446    $compose->setTXTBody(rc_wordwrap($body, 75, "\r\n"));
1447    $compose->addAttachment($report, 'message/disposition-notification', 'MDNPart2.txt', false, '7bit', 'inline');
1448
1449    $sent = rcmail_deliver_message($compose, $identity['email'], $mailto, $smtp_error, $body_file);
1450
1451    if ($sent)
1452    {
1453      $IMAP->set_flag($message->uid, 'MDNSENT');
1454      return true;
1455    }
1456  }
1457 
1458  return false;
1459}
1460
1461function rcmail_search_filter($attrib)
1462{
1463  global $OUTPUT, $CONFIG;
1464
1465  if (!strlen($attrib['id']))
1466    $attrib['id'] = 'rcmlistfilter';
1467
1468  $attrib['onchange'] = JS_OBJECT_NAME.'.filter_mailbox(this.value)';
1469 
1470  /*
1471    RFC3501 (6.4.4): 'ALL', 'RECENT',
1472    'ANSWERED', 'DELETED', 'FLAGGED', 'SEEN',
1473    'UNANSWERED', 'UNDELETED', 'UNFLAGGED', 'UNSEEN',
1474    'NEW', // = (RECENT UNSEEN)
1475    'OLD' // = NOT RECENT
1476  */
1477
1478  $select_filter = new html_select($attrib);
1479  $select_filter->add(rcube_label('all'), 'ALL');
1480  $select_filter->add(rcube_label('unread'), 'UNSEEN');
1481  $select_filter->add(rcube_label('flagged'), 'FLAGGED');
1482  $select_filter->add(rcube_label('unanswered'), 'UNANSWERED');
1483  if (!$CONFIG['skip_deleted'])
1484    $select_filter->add(rcube_label('deleted'), 'DELETED');
1485
1486  $out = $select_filter->show($_SESSION['search_filter']);
1487
1488  $OUTPUT->add_gui_object('search_filter', $attrib['id']);
1489
1490  return $out;                                                                         
1491}
1492
1493
1494// register UI objects
1495$OUTPUT->add_handlers(array(
1496  'mailboxlist' => 'rcmail_mailbox_list',
1497  'messages' => 'rcmail_message_list',
1498  'messagecountdisplay' => 'rcmail_messagecount_display',
1499  'quotadisplay' => 'rcmail_quota_display',
1500  'mailboxname' => 'rcmail_mailbox_name_display',
1501  'messageheaders' => 'rcmail_message_headers',
1502  'messagebody' => 'rcmail_message_body',
1503  'messagecontentframe' => 'rcmail_messagecontent_frame',
1504  'messagepartframe' => 'rcmail_message_part_frame',
1505  'messagepartcontrols' => 'rcmail_message_part_controls',
1506  'searchfilter' => 'rcmail_search_filter',
1507  'searchform' => array($OUTPUT, 'search_form'),
1508));
1509
1510?>
Note: See TracBrowser for help on using the repository browser.