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

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