source: github/program/steps/mail/func.inc @ 166b615

HEADcourier-fixdev-browser-capabilitiespdorelease-0.6release-0.7release-0.8
Last change on this file since 166b615 was 166b615, checked in by alecpl <alec@…>, 5 years ago
  • Added option to disable displaying of attached images below the message body
  • Property mode set to 100644
File size: 36.0 KB
Line 
1<?php
2
3/*
4 +-----------------------------------------------------------------------+
5 | program/steps/mail/func.inc                                           |
6 |                                                                       |
7 | This file is part of the RoundCube Webmail client                     |
8 | Copyright (C) 2005-2008, 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('lib/enriched.inc');
23require_once('include/rcube_smtp.inc');
24
25
26$EMAIL_ADDRESS_PATTERN = '/([a-z0-9][a-z0-9\-\.\+\_]*@[a-z0-9]([a-z0-9\-][.]?)*[a-z0-9]\\.[a-z]{2,5})/i';
27
28if (empty($_SESSION['mbox']))
29  $_SESSION['mbox'] = $IMAP->get_mailbox_name();
30
31// set imap properties and session vars
32if ($mbox = get_input_value('_mbox', RCUBE_INPUT_GPC))
33  $IMAP->set_mailbox(($_SESSION['mbox'] = $mbox));
34
35if (!empty($_GET['_page']))
36  $IMAP->set_page(($_SESSION['page'] = intval($_GET['_page'])));
37
38// set mailbox to INBOX if not set
39if (empty($_SESSION['mbox']))
40  $_SESSION['mbox'] = $IMAP->get_mailbox_name();
41
42// set default sort col/order to session
43if (!isset($_SESSION['sort_col']))
44  $_SESSION['sort_col'] = $CONFIG['message_sort_col'];
45if (!isset($_SESSION['sort_order']))
46  $_SESSION['sort_order'] = $CONFIG['message_sort_order'];
47
48// set message set for search result
49if (!empty($_REQUEST['_search']) && isset($_SESSION['search'][$_REQUEST['_search']]))
50  {
51  $IMAP->set_search_set($_SESSION['search'][$_REQUEST['_search']]);
52  $OUTPUT->set_env('search_request', $_REQUEST['_search']);
53  $OUTPUT->set_env('search_text', $_SESSION['last_text_search']);
54  }
55
56
57// set current mailbox in client environment
58$OUTPUT->set_env('mailbox', $IMAP->get_mailbox_name());
59$OUTPUT->set_env('quota', $IMAP->get_capability('quota'));
60
61if ($CONFIG['trash_mbox'])
62  $OUTPUT->set_env('trash_mailbox', $CONFIG['trash_mbox']);
63if ($CONFIG['drafts_mbox'])
64  $OUTPUT->set_env('drafts_mailbox', $CONFIG['drafts_mbox']);
65if ($CONFIG['junk_mbox'])
66  $OUTPUT->set_env('junk_mailbox', $CONFIG['junk_mbox']);
67
68if (!$OUTPUT->ajax_call)
69  rcube_add_label('checkingmail', 'deletemessage', 'movemessagetotrash', 'movingmessage');
70
71// set page title
72if (empty($RCMAIL->action) || $RCMAIL->action == 'list')
73  $OUTPUT->set_pagetitle(rcmail_localize_foldername($IMAP->get_mailbox_name()));
74
75
76
77/**
78 * return the message list as HTML table
79 */
80function rcmail_message_list($attrib)
81  {
82  global $IMAP, $CONFIG, $COMM_PATH, $OUTPUT;
83
84  $skin_path = $CONFIG['skin_path'];
85  $image_tag = '<img src="%s%s" alt="%s" border="0" />';
86
87  // check to see if we have some settings for sorting
88  $sort_col   = $_SESSION['sort_col'];
89  $sort_order = $_SESSION['sort_order'];
90 
91  // add some labels to client
92  rcube_add_label('from', 'to');
93
94  // get message headers
95  $a_headers = $IMAP->list_headers('', '', $sort_col, $sort_order);
96
97  // add id to message list table if not specified
98  if (!strlen($attrib['id']))
99    $attrib['id'] = 'rcubemessagelist';
100
101  // allow the following attributes to be added to the <table> tag
102  $attrib_str = create_attrib_string($attrib, array('style', 'class', 'id', 'cellpadding', 'cellspacing', 'border', 'summary'));
103
104  $out = '<table' . $attrib_str . ">\n";
105
106
107  // define list of cols to be displayed
108  $a_show_cols = is_array($CONFIG['list_cols']) ? $CONFIG['list_cols'] : array('subject');
109  $a_sort_cols = array('subject', 'date', 'from', 'to', 'size');
110
111  $mbox = $IMAP->get_mailbox_name();
112 
113  // show 'to' instead of from in sent messages
114  if (($mbox==$CONFIG['sent_mbox'] || $mbox==$CONFIG['drafts_mbox']) && ($f = array_search('from', $a_show_cols))
115      && !array_search('to', $a_show_cols))
116    $a_show_cols[$f] = 'to';
117 
118  // add col definition
119  $out .= '<colgroup>';
120  $out .= '<col class="icon" />';
121
122  foreach ($a_show_cols as $col)
123    $out .= sprintf('<col class="%s" />', $col);
124
125  $out .= '<col class="icon" />';
126  $out .= "</colgroup>\n";
127
128  // add table title
129  $out .= "<thead><tr>\n<td class=\"icon\">&nbsp;</td>\n";
130
131  $javascript = '';
132  foreach ($a_show_cols as $col)
133    {
134    // get column name
135    $col_name = Q(rcube_label($col));
136
137    // make sort links
138    $sort = '';
139    if (in_array($col, $a_sort_cols))
140      {
141      // have buttons configured
142      if (!empty($attrib['sortdescbutton']) || !empty($attrib['sortascbutton']))
143        {
144        $sort = '&nbsp;&nbsp;';
145
146        // asc link
147        if (!empty($attrib['sortascbutton']))
148          {
149          $sort .= $OUTPUT->button(array(
150            'command' => 'sort',
151            'prop' => $col.'_ASC',
152            'image' => $attrib['sortascbutton'],
153            'align' => 'absmiddle',
154            'title' => 'sortasc'));
155          }       
156       
157        // desc link
158        if (!empty($attrib['sortdescbutton']))
159          {
160          $sort .= $OUTPUT->button(array(
161            'command' => 'sort',
162            'prop' => $col.'_DESC',
163            'image' => $attrib['sortdescbutton'],
164            'align' => 'absmiddle',
165            'title' => 'sortdesc'));
166          }
167        }
168      // just add a link tag to the header
169      else
170        {
171        $col_name = sprintf(
172          '<a href="./#sort" onclick="return %s.command(\'sort\',\'%s\',this)" title="%s">%s</a>',
173          JS_OBJECT_NAME,
174          $col,
175          rcube_label('sortby'),
176          $col_name);
177        }
178      }
179     
180    $sort_class = $col==$sort_col ? " sorted$sort_order" : '';
181
182    // put it all together
183    $out .= '<td class="'.$col.$sort_class.'" id="rcmHead'.$col.'">' . "$col_name$sort</td>\n";   
184    }
185
186  $out .= '<td class="icon">'.($attrib['attachmenticon'] ? sprintf($image_tag, $skin_path, $attrib['attachmenticon'], '') : '')."</td>\n";
187  $out .= "</tr></thead>\n<tbody>\n";
188
189  // no messages in this mailbox
190  if (!sizeof($a_headers))
191    $OUTPUT->show_message('nomessagesfound', 'notice');
192
193
194  $a_js_message_arr = array();
195
196  // create row for each message
197  foreach ($a_headers as $i => $header)  //while (list($i, $header) = each($a_headers))
198    {
199    $message_icon = $attach_icon = '';
200    $js_row_arr = array();
201    $zebra_class = $i%2 ? 'even' : 'odd';
202
203    // set messag attributes to javascript array
204    if ($header->deleted)
205      $js_row_arr['deleted'] = true;
206    if (!$header->seen)
207      $js_row_arr['unread'] = true;
208    if ($header->answered)
209      $js_row_arr['replied'] = true;
210    // set message icon 
211    if ($attrib['deletedicon'] && $header->deleted)
212      $message_icon = $attrib['deletedicon'];
213    else if ($attrib['unreadicon'] && !$header->seen)
214      $message_icon = $attrib['unreadicon'];
215    else if ($attrib['repliedicon'] && $header->answered)
216      $message_icon = $attrib['repliedicon'];
217    else if ($attrib['messageicon'])
218      $message_icon = $attrib['messageicon'];
219   
220    // set attachment icon
221    if ($attrib['attachmenticon'] && preg_match("/multipart\/[mr]/i", $header->ctype))
222      $attach_icon = $attrib['attachmenticon'];
223       
224    $out .= sprintf('<tr id="rcmrow%d" class="message%s%s %s">'."\n",
225                    $header->uid,
226                    $header->seen ? '' : ' unread',
227                    $header->deleted ? ' deleted' : '',
228                    $zebra_class);   
229   
230    $out .= sprintf("<td class=\"icon\">%s</td>\n", $message_icon ? sprintf($image_tag, $skin_path, $message_icon, '') : '');
231
232    if (!empty($header->charset))
233      $IMAP->set_charset($header->charset);
234 
235    // format each col
236    foreach ($a_show_cols as $col)
237      {
238      if ($col=='from' || $col=='to')
239        $cont = Q(rcmail_address_string($header->$col, 3, $attrib['addicon']), 'show');
240      else if ($col=='subject')
241        {
242        $action = $mbox==$CONFIG['drafts_mbox'] ? 'compose' : 'show';
243        $uid_param = $mbox==$CONFIG['drafts_mbox'] ? '_draft_uid' : '_uid';
244        $cont = Q($IMAP->decode_header($header->$col));
245        if (empty($cont)) $cont = Q(rcube_label('nosubject'));
246        $cont = sprintf('<a href="%s" onclick="return rcube_event.cancel(event)">%s</a>', Q(rcmail_url($action, array($uid_param=>$header->uid, '_mbox'=>$mbox))), $cont);
247        }
248      else if ($col=='size')
249        $cont = show_bytes($header->$col);
250      else if ($col=='date')
251        $cont = format_date($header->date);
252      else
253        $cont = Q($header->$col);
254       
255      $out .= '<td class="'.$col.'">' . $cont . "</td>\n";
256      }
257
258    $out .= sprintf("<td class=\"icon\">%s</td>\n", $attach_icon ? sprintf($image_tag, $skin_path, $attach_icon, '') : '');
259    $out .= "</tr>\n";
260   
261    if (sizeof($js_row_arr))
262      $a_js_message_arr[$header->uid] = $js_row_arr;
263    }
264 
265  // complete message table
266  $out .= "</tbody></table>\n";
267 
268 
269  $message_count = $IMAP->messagecount();
270 
271  // set client env
272  $OUTPUT->add_gui_object('mailcontframe', 'mailcontframe');
273  $OUTPUT->add_gui_object('messagelist', $attrib['id']);
274  $OUTPUT->set_env('messagecount', $message_count);
275  $OUTPUT->set_env('current_page', $IMAP->list_page);
276  $OUTPUT->set_env('pagecount', ceil($message_count/$IMAP->page_size));
277  $OUTPUT->set_env('sort_col', $sort_col);
278  $OUTPUT->set_env('sort_order', $sort_order);
279 
280  if ($attrib['messageicon'])
281    $OUTPUT->set_env('messageicon', $skin_path . $attrib['messageicon']);
282  if ($attrib['deletedicon'])
283    $OUTPUT->set_env('deletedicon', $skin_path . $attrib['deletedicon']);
284  if ($attrib['unreadicon'])
285    $OUTPUT->set_env('unreadicon', $skin_path . $attrib['unreadicon']);
286  if ($attrib['repliedicon'])
287    $OUTPUT->set_env('repliedicon', $skin_path . $attrib['repliedicon']);
288  if ($attrib['attachmenticon'])
289    $OUTPUT->set_env('attachmenticon', $skin_path . $attrib['attachmenticon']);
290 
291  $OUTPUT->set_env('messages', $a_js_message_arr);
292  $OUTPUT->set_env('coltypes', $a_show_cols);
293 
294  $OUTPUT->include_script('list.js');
295 
296  return $out;
297  }
298
299
300/**
301 * return javascript commands to add rows to the message list
302 */
303function rcmail_js_message_list($a_headers, $insert_top=FALSE)
304  {
305  global $CONFIG, $IMAP, $OUTPUT;
306
307  $a_show_cols = is_array($CONFIG['list_cols']) ? $CONFIG['list_cols'] : array('subject');
308  $mbox = $IMAP->get_mailbox_name();
309
310  // show 'to' instead of from in sent messages
311  if (($mbox == $CONFIG['sent_mbox'] || $mbox == $CONFIG['drafts_mbox'])
312      && (($f = array_search('from', $a_show_cols)) !== false) && array_search('to', $a_show_cols) === false)
313    $a_show_cols[$f] = 'to';
314
315  $OUTPUT->command('set_message_coltypes', $a_show_cols);
316
317  // loop through message headers
318  foreach ($a_headers as $n => $header)
319    {
320    $a_msg_cols = array();
321    $a_msg_flags = array();
322   
323    if (empty($header))
324      continue;
325
326    if (!empty($header->charset))
327      $IMAP->set_charset($header->charset);
328
329    // format each col; similar as in rcmail_message_list()
330    foreach ($a_show_cols as $col)
331      {
332      if ($col=='from' || $col=='to')
333        $cont = Q(rcmail_address_string($header->$col, 3), 'show');
334      else if ($col=='subject')
335        {
336        $action = $mbox==$CONFIG['drafts_mbox'] ? 'compose' : 'show';
337        $uid_param = $mbox==$CONFIG['drafts_mbox'] ? '_draft_uid' : '_uid';
338        $cont = Q($IMAP->decode_header($header->$col));
339        if (!$cont) $cont = Q(rcube_label('nosubject'));
340        $cont = sprintf('<a href="%s" onclick="return rcube_event.cancel(event)">%s</a>', Q(rcmail_url($action, array($uid_param=>$header->uid, '_mbox'=>$mbox))), $cont);
341        }
342      else if ($col=='size')
343        $cont = show_bytes($header->$col);
344      else if ($col=='date')
345        $cont = format_date($header->date);
346      else
347        $cont = Q($header->$col);
348         
349      $a_msg_cols[$col] = $cont;
350      }
351
352    $a_msg_flags['deleted'] = $header->deleted ? 1 : 0;
353    $a_msg_flags['unread'] = $header->seen ? 0 : 1;
354    $a_msg_flags['replied'] = $header->answered ? 1 : 0;
355    $OUTPUT->command('add_message_row',
356      $header->uid,
357      $a_msg_cols,
358      $a_msg_flags,
359      preg_match("/multipart\/m/i", $header->ctype),
360      $insert_top);
361    }
362  }
363
364
365/**
366 * return an HTML iframe for loading mail content
367 */
368function rcmail_messagecontent_frame($attrib)
369  {
370  global $OUTPUT;
371 
372  if (empty($attrib['id']))
373    $attrib['id'] = 'rcmailcontentwindow';
374
375  // allow the following attributes to be added to the <iframe> tag
376  $attrib_str = create_attrib_string($attrib, array('id', 'class', 'style', 'src', 'width', 'height', 'frameborder'));
377  $framename = $attrib['id'];
378
379  $out = sprintf('<iframe name="%s"%s></iframe>'."\n",
380         $framename,
381         $attrib_str);
382
383  $OUTPUT->set_env('contentframe', $framename);
384  $OUTPUT->set_env('blankpage', $attrib['src'] ? $OUTPUT->abs_url($attrib['src']) : 'program/blank.gif');
385
386  return $out;
387  }
388
389
390/**
391 *
392 */
393function rcmail_messagecount_display($attrib)
394  {
395  global $IMAP, $OUTPUT;
396 
397  if (!$attrib['id'])
398    $attrib['id'] = 'rcmcountdisplay';
399
400  $OUTPUT->add_gui_object('countdisplay', $attrib['id']);
401
402  // allow the following attributes to be added to the <span> tag
403  $attrib_str = create_attrib_string($attrib, array('style', 'class', 'id'));
404
405 
406  $out = '<span' . $attrib_str . '>';
407  $out .= rcmail_get_messagecount_text();
408  $out .= '</span>';
409  return $out;
410  }
411
412
413/**
414 *
415 */
416function rcmail_quota_display($attrib)
417  {
418  global $OUTPUT, $COMM_PATH;
419
420  if (!$attrib['id'])
421    $attrib['id'] = 'rcmquotadisplay';
422
423  if(isset($attrib['display']))
424    $_SESSION['quota_display'] = $attrib['display'];
425
426  $OUTPUT->add_gui_object('quotadisplay', $attrib['id']);
427
428  // allow the following attributes to be added to the <span> tag
429  $attrib_str = create_attrib_string($attrib, array('style', 'class', 'id', 'display'));
430
431  $out = '<span' . $attrib_str . '>';
432  $out .= rcmail_quota_content();
433  $out .= '</span>';
434  return $out;
435  }
436
437
438/**
439 *
440 */
441function rcmail_quota_content($quota=NULL)
442  {
443  global $IMAP, $COMM_PATH;
444
445  $display = isset($_SESSION['quota_display']) ? $_SESSION['quota_display'] : '';
446
447  if (is_array($quota) && !empty($quota['used']) && !empty($quota['total']))
448    {
449      if (!isset($quota['percent']))
450        $quota['percent'] = $quota['used'] / $quota['total'];
451    }
452  elseif (!$IMAP->get_capability('QUOTA'))
453    return rcube_label('unknown');
454  else
455    $quota = $IMAP->get_quota();
456
457  if ($quota)
458    {
459    $quota_text = sprintf('%s / %s (%.0f%%)',
460                          show_bytes($quota['used'] * 1024),
461                          show_bytes($quota['total'] * 1024),
462                          $quota['percent']);
463
464    // show quota as image (by Brett Patterson)
465    if ($display == 'image' && function_exists('imagegif'))
466      {
467      $attrib = array('width' => 100, 'height' => 14);
468      $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" />',
469                            $quota['used'], $quota['total'],
470                            $attrib['width'], $attrib['height'],
471                            $attrib['width'], $attrib['height'],
472                            $quota_text,
473                            show_bytes($quota["used"] * 1024),
474                            show_bytes($quota["total"] * 1024));
475      }
476    }
477  else
478    $quota_text = rcube_label('unlimited');
479
480  return $quota_text;
481  }
482
483
484/**
485 *
486 */
487function rcmail_get_messagecount_text($count=NULL, $page=NULL)
488  {
489  global $IMAP, $MESSAGE;
490 
491  if (isset($MESSAGE->index))
492    {
493    return rcube_label(array('name' => 'messagenrof',
494                             'vars' => array('nr'  => $MESSAGE->index+1,
495                                             'count' => $count!==NULL ? $count : $IMAP->messagecount())));
496    }
497
498  if ($page===NULL)
499    $page = $IMAP->list_page;
500   
501  $start_msg = ($page-1) * $IMAP->page_size + 1;
502  $max = $count!==NULL ? $count : $IMAP->messagecount();
503
504  if ($max==0)
505    $out = rcube_label('mailboxempty');
506  else
507    $out = rcube_label(array('name' => 'messagesfromto',
508                              'vars' => array('from'  => $start_msg,
509                                              'to'    => min($max, $start_msg + $IMAP->page_size - 1),
510                                              'count' => $max)));
511
512  return Q($out);
513  }
514
515
516/**
517 * Convert the given message part to proper HTML
518 * which can be displayed the message view
519 *
520 * @param object rcube_message_part Message part
521 * @param bool  True if external objects (ie. images ) are allowed
522 * @param bool  True if part should be converted to plaintext
523 * @return string Formatted HTML string
524 */
525function rcmail_print_body($part, $safe=false, $plain=false)
526{
527  global $REMOTE_OBJECTS;
528 
529  // convert html to text/plain
530  if ($part->ctype_secondary == 'html' && $plain) {
531    $txt = new html2text($part->body, false, true);
532    $body = $txt->get_text();
533    $part->ctype_secondary = 'plain';
534  }
535  // text/html
536  else if ($part->ctype_secondary == 'html') {
537    // charset was converted to UTF-8 in rcube_imap::get_message_part() -> change charset specification in HTML accordingly
538    $html = $part->body;
539    if(preg_match('/(\s+content=[\'"]\w+\/\w+;\s+charset)=([a-z0-9-]+)/i', $html))
540      $html = preg_replace('/(\s+content=[\'"]\w+\/\w+;\s+charset)=([a-z0-9-]+)/i', '\\1='.RCMAIL_CHARSET, $html);
541    else
542      $html = substr_replace($html, '<meta http-equiv="Content-Type" content="text/html; charset='.RCMAIL_CHARSET.'" />', intval(stripos($html, '</head>')), 0);
543   
544    // clean HTML with washhtml by Frederic Motte
545    $body = washtml::wash($html, array(
546      'show_washed' => false,
547      'allow_remote' => $safe,
548      'blocked_src' => "./program/blocked.gif",
549      'charset' => RCMAIL_CHARSET,
550      'cid_map' => $part->replaces,
551      ), $full_inline);
552
553    $REMOTE_OBJECTS = !$full_inline;
554
555    return $body;
556  }
557  // text/enriched
558  else if ($part->ctype_secondary=='enriched') {
559    $part->ctype_secondary = 'html';
560    return Q(enriched_to_html($body), 'show');
561  }
562  else
563    $body = $part->body;
564
565
566  /**** assert plaintext ****/
567
568  // make links and email-addresses clickable
569  $convert_patterns = $convert_replaces = $replace_strings = array();
570 
571  $url_chars = 'a-z0-9_\-\+\*\$\/&%=@#:;';
572  $url_chars_within = '\?\.~,!';
573
574  $convert_patterns[] = "/([\w]+):\/\/([a-z0-9\-\.]+[a-z]{2,4}([$url_chars$url_chars_within]*[$url_chars])?)/ie";
575  $convert_replaces[] = "rcmail_str_replacement('<a href=\"\\1://\\2\" target=\"_blank\">\\1://\\2</a>', \$replace_strings)";
576
577  $convert_patterns[] = "/([^\/:]|\s)(www\.)([a-z0-9\-]{2,}[a-z]{2,4}([$url_chars$url_chars_within]*[$url_chars])?)/ie";
578  $convert_replaces[] = "rcmail_str_replacement('\\1<a href=\"http://\\2\\3\" target=\"_blank\">\\2\\3</a>', \$replace_strings)";
579 
580  $convert_patterns[] = '/([a-z0-9][a-z0-9\-\.\+\_]*@[a-z0-9]([a-z0-9\-][.]?)*[a-z0-9]\\.[a-z]{2,5})/ie';
581  $convert_replaces[] = "rcmail_str_replacement('<a href=\"mailto:\\1\" onclick=\"return ".JS_OBJECT_NAME.".command(\'compose\',\'\\1\',this)\">\\1</a>', \$replace_strings)";
582 
583//    if ($part->ctype_parameters['format'] != 'flowed')
584//      $body = wordwrap(trim($body), 80);
585
586  // search for patterns like links and e-mail addresses
587  $body = preg_replace($convert_patterns, $convert_replaces, $body);
588
589  // split body into single lines
590  $a_lines = preg_split('/\r?\n/', $body);
591  $quote_level = 0;
592
593  // colorize quoted parts
594  for ($n=0; $n < sizeof($a_lines); $n++) {
595    $line = $a_lines[$n];
596    $quotation = '';
597    $q = 0;
598   
599    if (preg_match('/^(>+\s*)+/', $line, $regs)) {
600      $q    = strlen(preg_replace('/\s/', '', $regs[0]));
601      $line = substr($line, strlen($regs[0]));
602
603      if ($q > $quote_level)
604        $quotation = str_repeat('<blockquote>', $q - $quote_level);
605      else if ($q < $quote_level)
606        $quotation = str_repeat("</blockquote>", $quote_level - $q);
607    }
608    else if ($quote_level > 0)
609      $quotation = str_repeat("</blockquote>", $quote_level);
610
611    $quote_level = $q;
612    $a_lines[$n] = $quotation . Q($line, 'replace', false);  // htmlquote plaintext
613  }
614
615  // insert the links for urls and mailtos
616  $body = preg_replace("/##string_replacement\{([0-9]+)\}##/e", "\$replace_strings[\\1]", join("\n", $a_lines));
617 
618  return "<div class=\"pre\">".$body."\n</div>";
619  }
620
621
622
623/**
624 * add a string to the replacement array and return a replacement string
625 */
626function rcmail_str_replacement($str, &$rep)
627  {
628  static $count = 0;
629  $rep[$count] = stripslashes($str);
630  return "##string_replacement{".($count++)."}##";
631  }
632
633
634
635/**
636 * return table with message headers
637 */
638function rcmail_message_headers($attrib, $headers=NULL)
639  {
640  global $IMAP, $OUTPUT, $MESSAGE;
641  static $sa_attrib;
642 
643  // keep header table attrib
644  if (is_array($attrib) && !$sa_attrib)
645    $sa_attrib = $attrib;
646  else if (!is_array($attrib) && is_array($sa_attrib))
647    $attrib = $sa_attrib;
648 
649 
650  if (!isset($MESSAGE))
651    return FALSE;
652
653  // get associative array of headers object
654  if (!$headers)
655    $headers = is_object($MESSAGE->headers) ? get_object_vars($MESSAGE->headers) : $MESSAGE->headers;
656   
657  // add empty subject if none exsists
658  if (empty($headers['subject']))
659    $headers['subject'] = rcube_label('nosubject');
660 
661  $header_count = 0;
662 
663  // allow the following attributes to be added to the <table> tag
664  $attrib_str = create_attrib_string($attrib, array('style', 'class', 'id', 'cellpadding', 'cellspacing', 'border', 'summary'));
665  $out = '<table' . $attrib_str . ">\n";
666
667  // show these headers
668  $standard_headers = array('subject', 'from', 'organization', 'to', 'cc', 'bcc', 'reply-to', 'date');
669 
670  foreach ($standard_headers as $hkey)
671    {
672    if (!$headers[$hkey])
673      continue;
674
675    if ($hkey=='date' && !empty($headers[$hkey]))
676      $header_value = format_date($headers[$hkey]);
677    else if (in_array($hkey, array('from', 'to', 'cc', 'bcc', 'reply-to')))
678      $header_value = Q(rcmail_address_string($headers[$hkey], NULL, $attrib['addicon']), 'show');
679    else
680      $header_value = Q($IMAP->decode_header($headers[$hkey]));
681
682    $out .= "\n<tr>\n";
683    $out .= '<td class="header-title">'.Q(rcube_label($hkey)).":&nbsp;</td>\n";
684    $out .= '<td class="'.$hkey.'" width="90%">'.$header_value."</td>\n</tr>";
685    $header_count++;
686    }
687
688  $out .= "\n</table>\n\n";
689
690  return $header_count ? $out : ''; 
691  }
692
693
694/**
695 * Handler for the 'messagebody' GUI object
696 *
697 * @param array Named parameters
698 * @return string HTML content showing the message body
699 */
700function rcmail_message_body($attrib)
701  {
702  global $CONFIG, $OUTPUT, $MESSAGE, $IMAP, $REMOTE_OBJECTS;
703 
704  if (!is_array($MESSAGE->parts) && empty($MESSAGE->body))
705    return '';
706   
707  if (!$attrib['id'])
708    $attrib['id'] = 'rcmailMsgBody';
709
710  $safe_mode = $MESSAGE->is_safe || intval($_GET['_safe']);
711  $out = '';
712 
713  $header_attrib = array();
714  foreach ($attrib as $attr => $value)
715    if (preg_match('/^headertable([a-z]+)$/i', $attr, $regs))
716      $header_attrib[$regs[1]] = $value;
717
718  if (!empty($MESSAGE->parts))
719    {
720    foreach ($MESSAGE->parts as $i => $part)
721      {
722      if ($part->type == 'headers')
723        $out .= rcmail_message_headers(sizeof($header_attrib) ? $header_attrib : NULL, $part->headers);
724      else if ($part->type == 'content')
725        {
726        if (empty($part->ctype_parameters) || empty($part->ctype_parameters['charset']))
727          $part->ctype_parameters['charset'] = $MESSAGE->headers->charset;
728
729        // fetch part if not available
730        if (!isset($part->body))
731          $part->body = $MESSAGE->get_part_content($part->mime_id);
732
733        $body = rcmail_print_body($part, $safe_mode, !$CONFIG['prefer_html']);
734       
735        if ($part->ctype_secondary == 'html')
736          $out .= html::div('message-htmlpart', rcmail_html4inline($body, $attrib['id']));
737        else
738          $out .= html::div('message-part', $body);
739        }
740      }
741    }
742  else
743    $out .= html::div('message-part', html::div('pre', Q($MESSAGE->body)));
744
745
746  $ctype_primary = strtolower($MESSAGE->structure->ctype_primary);
747  $ctype_secondary = strtolower($MESSAGE->structure->ctype_secondary);
748
749  // list images after mail body
750  if (get_boolean($attrib['showimages'])
751        && $CONFIG['inline_images']
752        && $ctype_primary == 'multipart'
753        && !empty($MESSAGE->attachments)
754        && !strstr($message_body, '<html'))
755    {
756    foreach ($MESSAGE->attachments as $attach_prop) {
757      if (strpos($attach_prop->mimetype, 'image/') === 0) {
758        $out .= html::tag('hr') . html::p(array('align' => "center"),
759          html::img(array(
760            'src' => $MESSAGE->get_part_url($attach_prop->mime_id),
761            'title' => $attach_prop->filename,
762            'alt' => $attach_prop->filename,
763          )));
764        }
765    }
766  }
767 
768  // tell client that there are blocked remote objects
769  if ($REMOTE_OBJECTS && !$safe_mode)
770    $OUTPUT->set_env('blockedobjects', true);
771
772  return html::div($attrib, $out);
773  }
774
775
776
777/**
778 * modify a HTML message that it can be displayed inside a HTML page
779 */
780function rcmail_html4inline($body, $container_id)
781  {
782  $base_url = "";
783  $last_style_pos = 0;
784  $body_lc = strtolower($body);
785 
786  // check for <base href>
787  if (preg_match(($base_reg = '/(<base.*href=["\']?)([hftps]{3,5}:\/{2}[^"\'\s]+)([^<]*>)/i'), $body, $base_regs))
788    $base_url = $base_regs[2];
789 
790  // find STYLE tags
791  while (($pos = strpos($body_lc, '<style', $last_style_pos)) && ($pos2 = strpos($body_lc, '</style>', $pos)))
792    {
793    $pos = strpos($body_lc, '>', $pos)+1;
794
795    // replace all css definitions with #container [def]
796    $styles = rcmail_mod_css_styles(substr($body, $pos, $pos2-$pos), $container_id, $base_url);
797
798    $body = substr($body, 0, $pos) . $styles . substr($body, $pos2);
799    $body_lc = strtolower($body);
800    $last_style_pos = $pos2;
801    }
802
803  // resolve <base href>
804  if ($base_url)
805    {
806    $body = preg_replace('/(src|background|href)=(["\']?)([\.\/]+[^"\'\s]+)(\2|\s|>)/Uie', "'\\1=\"'.make_absolute_url('\\3', '$base_url').'\"'", $body);
807    $body = preg_replace('/(url\s*\()(["\']?)([\.\/]+[^"\'\)\s]+)(\2)\)/Uie', "'\\1\''.make_absolute_url('\\3', '$base_url').'\')'", $body);
808    $body = preg_replace($base_reg, '', $body);
809    }
810   
811  // modify HTML links to open a new window if clicked
812  $body = preg_replace('/<(a|link)\s+([^>]+)>/Uie', "rcmail_alter_html_link('\\1','\\2', '$container_id');", $body);
813
814  // add comments arround html and other tags
815  $out = preg_replace(array(
816      '/(<!DOCTYPE[^>]*>)/i',
817      '/(<\?xml[^>]*>)/i',
818      '/(<\/?html[^>]*>)/i',
819      '/(<\/?head[^>]*>)/i',
820      '/(<title[^>]*>.*<\/title>)/Ui',
821      '/(<\/?meta[^>]*>)/i'),
822    '<!--\\1-->',
823    $body);
824
825  $out = preg_replace(
826    array('/<body([^>]*)>/i', '/<\/body>/i'),
827    array('<div class="rcmBody"\\1>', '</div>'),
828    $out);
829
830  // quote <? of php and xml files that are specified as text/html
831  $out = preg_replace(array('/<\?/', '/\?>/'), array('&lt;?', '?&gt;'), $out);
832
833  return $out;
834  }
835
836
837/**
838 * parse link attributes and set correct target
839 */
840function rcmail_alter_html_link($tag, $attrs, $container_id)
841  {
842  $attrib = parse_attrib_string($attrs);
843
844  if ($tag == 'link' && preg_match('/^https?:\/\//i', $attrib['href']))
845    $attrib['href'] = "./bin/modcss.php?u=" . urlencode($attrib['href']) . "&amp;c=" . urlencode($container_id);
846
847  else if (stristr((string)$attrib['href'], 'mailto:'))
848    $attrib['onclick'] = sprintf(
849      "return %s.command('compose','%s',this)",
850      JS_OBJECT_NAME,
851      JQ(substr($attrib['href'], 7)));
852
853  else if (!empty($attrib['href']) && $attrib['href']{0}!='#')
854    $attrib['target'] = '_blank';
855
856  return "<$tag" . create_attrib_string($attrib, array('href','name','target','onclick','id','class','style','title','rel','type','media')) . ' />';
857  }
858
859
860/**
861 * decode address string and re-format it as HTML links
862 */
863function rcmail_address_string($input, $max=NULL, $addicon=NULL)
864  {
865  global $IMAP, $PRINT_MODE, $CONFIG, $OUTPUT, $EMAIL_ADDRESS_PATTERN;
866
867  $a_parts = $IMAP->decode_address_list($input);
868
869  if (!sizeof($a_parts))
870    return $input;
871
872  $c = count($a_parts);
873  $j = 0;
874  $out = '';
875
876  foreach ($a_parts as $part)
877    {
878    $j++;
879    if ($PRINT_MODE)
880      $out .= sprintf('%s &lt;%s&gt;', Q($part['name']), $part['mailto']);
881    else if (preg_match($EMAIL_ADDRESS_PATTERN, $part['mailto']))
882      {
883      $out .= sprintf('<a href="mailto:%s" onclick="return %s.command(\'compose\',\'%s\',this)" class="rcmContactAddress" title="%s">%s</a>',
884                      Q($part['mailto']),
885                      JS_OBJECT_NAME,
886                      JQ($part['mailto']),
887                      Q($part['mailto']),
888                      Q($part['name']));
889                     
890      if ($addicon)
891        $out .= sprintf('&nbsp;<a href="#add" onclick="return %s.command(\'add-contact\',\'%s\',this)" title="%s"><img src="%s%s" alt="add" border="0" /></a>',
892                        JS_OBJECT_NAME,
893                        urlencode($part['string']),
894                        rcube_label('addtoaddressbook'),
895                        $CONFIG['skin_path'],
896                        $addicon);
897      }
898    else
899      {
900      if ($part['name'])
901        $out .= Q($part['name']);
902      if ($part['mailto'])
903        $out .= (strlen($out) ? ' ' : '') . sprintf('&lt;%s&gt;', Q($part['mailto']));
904      }
905     
906    if ($c>$j)
907      $out .= ','.($max ? '&nbsp;' : ' ');
908       
909    if ($max && $j==$max && $c>$j)
910      {
911      $out .= '...';
912      break;
913      }       
914    }
915   
916  return $out;
917  }
918
919
920function rcmail_message_part_controls()
921  {
922  global $MESSAGE;
923 
924  $part = asciiwords(get_input_value('_part', RCUBE_INPUT_GPC));
925  if (!is_object($MESSAGE) || !is_array($MESSAGE->parts) || !($_GET['_uid'] && $_GET['_part']) || !$MESSAGE->mime_parts[$part])
926    return '';
927   
928  $part = $MESSAGE->mime_parts[$part];
929  $table = new html_table(array('cols' => 3));
930 
931  if (!empty($part->filename)) {
932    $table->add('title', Q(rcube_label('filename')));
933    $table->add(null, Q($part->filename));
934    $table->add(null, '[' . html::a('?'.str_replace('_frame=', '_download=', $_SERVER['QUERY_STRING']), Q(rcube_label('download'))) . ']');
935  }
936 
937  if (!empty($part->size)) {
938    $table->add('title', Q(rcube_label('filesize')));
939    $table->add(null, Q(show_bytes($part->size)));
940  }
941 
942  return $table->show($attrib);
943  }
944
945
946
947function rcmail_message_part_frame($attrib)
948  {
949  global $MESSAGE;
950 
951  $part = $MESSAGE->mime_parts[asciiwords(get_input_value('_part', RCUBE_INPUT_GPC))];
952  $ctype_primary = strtolower($part->ctype_primary);
953
954  $attrib['src'] = Q('./?'.str_replace('_frame=', ($ctype_primary=='text' ? '_show=' : '_preload='), $_SERVER['QUERY_STRING']));
955
956  $attrib_str = create_attrib_string($attrib, array('id', 'class', 'style', 'src', 'width', 'height'));
957  $out = '<iframe '. $attrib_str . "></iframe>";
958   
959  return $out;
960  }
961
962
963/**
964 * clear message composing settings
965 */
966function rcmail_compose_cleanup()
967  {
968  if (!isset($_SESSION['compose']))
969    return;
970
971  // remove attachment files from temp dir
972  if (is_array($_SESSION['compose']['attachments']))
973    foreach ($_SESSION['compose']['attachments'] as $attachment)
974      @unlink($attachment['path']);
975 
976  unset($_SESSION['compose']);
977  }
978 
979
980/**
981 * Send the given message compose object using the configured method
982 */
983function rcmail_deliver_message(&$message, $from, $mailto)
984{
985  global $CONFIG;
986
987  $msg_body = $message->get();
988  $headers = $message->headers();
989 
990  // send thru SMTP server using custom SMTP library
991  if ($CONFIG['smtp_server'])
992    {
993    // generate list of recipients
994    $a_recipients = array($mailto);
995 
996    if (strlen($headers['Cc']))
997      $a_recipients[] = $headers['Cc'];
998    if (strlen($headers['Bcc']))
999      $a_recipients[] = $headers['Bcc'];
1000 
1001    // clean Bcc from header for recipients
1002    $send_headers = $headers;
1003    unset($send_headers['Bcc']);
1004    // here too, it because txtHeaders() below use $message->_headers not only $send_headers
1005    unset($message->_headers['Bcc']);
1006
1007    // send message
1008    $smtp_response = array();
1009    $sent = smtp_mail($from, $a_recipients, ($foo = $message->txtHeaders($send_headers, true)), $msg_body, $smtp_response);
1010
1011    // log error
1012    if (!$sent)
1013      raise_error(array('code' => 800, 'type' => 'smtp', 'line' => __LINE__, 'file' => __FILE__,
1014                        'message' => "SMTP error: ".join("\n", $smtp_response)), TRUE, FALSE);
1015    }
1016 
1017  // send mail using PHP's mail() function
1018  else
1019    {
1020    // unset some headers because they will be added by the mail() function
1021    $headers_enc = $message->headers($headers);
1022    $headers_php = $message->_headers;
1023    unset($headers_php['To'], $headers_php['Subject']);
1024   
1025    // reset stored headers and overwrite
1026    $message->_headers = array();
1027    $header_str = $message->txtHeaders($headers_php);
1028 
1029    if (ini_get('safe_mode'))
1030      $sent = mail($headers_enc['To'], $headers_enc['Subject'], $msg_body, $header_str);
1031    else
1032      $sent = mail($headers_enc['To'], $headers_enc['Subject'], $msg_body, $header_str, "-f$from");
1033    }
1034 
1035  if ($sent)  // remove MDN headers after sending
1036    unset($headers['Return-Receipt-To'], $headers['Disposition-Notification-To']);
1037 
1038  $message->_headers = array();
1039  $message->headers($headers);
1040 
1041  return $sent;
1042}
1043
1044
1045function rcmail_send_mdn($uid)
1046{
1047  global $RCMAIL, $IMAP;
1048
1049  $message = new rcube_message($uid);
1050 
1051  if ($message->headers->mdn_to && !$message->headers->mdn_sent)
1052  {
1053    $identity = $RCMAIL->user->get_identity();
1054    $sender = format_email_recipient($identity['email'], $identity['name']);
1055    $recipient = array_shift($IMAP->decode_address_list($message->headers->mdn_to));
1056    $mailto = $recipient['mailto'];
1057
1058    $compose = new rcube_mail_mime($RCMAIL->config->header_delimiter());
1059    $compose->setParam(array(
1060      'text_encoding' => 'quoted-printable',
1061      'html_encoding' => 'quoted-printable',
1062      'head_encoding' => 'quoted-printable',
1063      'head_charset'  => RCMAIL_CHARSET,
1064      'html_charset'  => RCMAIL_CHARSET,
1065      'text_charset'  => RCMAIL_CHARSET,
1066    ));
1067   
1068    // compose headers array
1069    $headers = array(
1070      'Date' => date('r'),
1071      'From' => $sender,
1072      'To'   => $message->headers->mdn_to,
1073      'Subject' => rcube_label('receiptread') . ': ' . $message->subject,
1074      'Message-ID' => sprintf('<%s@%s>', md5(uniqid('rcmail'.rand(),true)), $RCMAIL->config->mail_domain($_SESSION['imap_host'])),
1075      'X-Sender' => $identity['email'],
1076      'Content-Type' => 'multipart/report; report-type=disposition-notification',
1077    );
1078   
1079    if ($agent = $RCMAIL->config->get('useragent'))
1080      $headers['User-Agent'] = $agent;
1081
1082    $body = rcube_label("yourmessage") . "\r\n\r\n" .
1083      "\t" . rcube_label("to") . ': ' . rcube_imap::decode_mime_string($message->headers->to, $message->headers->charset) . "\r\n" .
1084      "\t" . rcube_label("subject") . ': ' . $message->subject . "\r\n" .
1085      "\t" . rcube_label("sent") . ': ' . format_date($message->headers->date, $RCMAIL->config->get('date_long')) . "\r\n" .
1086      "\r\n" . rcube_label("receiptnote") . "\r\n";
1087   
1088    $ua = $RCMAIL->config->get('useragent', "RoundCube Webmail (Version ".RCMAIL_VERSION.")");
1089    $report = "Reporting-UA: $ua\r\n";
1090   
1091    if ($message->headers->to)
1092        $report .= "Original-Recipient: {$message->headers->to}\r\n";
1093   
1094    $report .= "Final-Recipient: rfc822; {$identity['email']}\r\n" .
1095               "Original-Message-ID: {$message->headers->messageID}\r\n" .
1096               "Disposition: manual-action/MDN-sent-manually; displayed\r\n";
1097   
1098    $compose->headers($headers);
1099    $compose->setTXTBody(wordwrap($body, 75, "\r\n"));
1100    $compose->addAttachment($report, 'message/disposition-notification', 'MDNPart2.txt', false, '7bit', 'inline');
1101
1102    $sent = rcmail_deliver_message($compose, $identity['email'], $mailto);
1103
1104    if ($sent)
1105    {
1106      $IMAP->set_flag($message->uid, 'MDNSENT');
1107      return true;
1108    }
1109  }
1110 
1111  return false;
1112}
1113
1114
1115// register UI objects
1116$OUTPUT->add_handlers(array(
1117  'mailboxlist' => 'rcmail_mailbox_list',
1118  'messages' => 'rcmail_message_list',
1119  'messagecountdisplay' => 'rcmail_messagecount_display',
1120  'quotadisplay' => 'rcmail_quota_display',
1121  'messageheaders' => 'rcmail_message_headers',
1122  'messagebody' => 'rcmail_message_body',
1123  'messagecontentframe' => 'rcmail_messagecontent_frame',
1124  'messagepartframe' => 'rcmail_message_part_frame',
1125  'messagepartcontrols' => 'rcmail_message_part_controls',
1126  'searchform' => array($OUTPUT, 'search_form'),
1127));
1128
1129?>
Note: See TracBrowser for help on using the repository browser.