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

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