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

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