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

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