source: github/program/steps/mail/func.inc @ 5b1de55

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