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

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