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

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