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

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