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

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