]> git.donarmstrong.com Git - roundcube.git/blob - program/steps/mail/func.inc
Imported Upstream version 0.2~alpha
[roundcube.git] / program / steps / mail / func.inc
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: func.inc 1494 2008-06-09 12:22:54Z alec $
19
20 */
21
22 require_once('lib/enriched.inc');
23 require_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
28 if (empty($_SESSION['mbox']))
29   $_SESSION['mbox'] = $IMAP->get_mailbox_name();
30
31 // set imap properties and session vars
32 if ($mbox = get_input_value('_mbox', RCUBE_INPUT_GPC))
33   $IMAP->set_mailbox(($_SESSION['mbox'] = $mbox));
34
35 if (!empty($_GET['_page']))
36   $IMAP->set_page(($_SESSION['page'] = intval($_GET['_page'])));
37
38 // set mailbox to INBOX if not set
39 if (empty($_SESSION['mbox']))
40   $_SESSION['mbox'] = $IMAP->get_mailbox_name();
41
42 // set default sort col/order to session
43 if (!isset($_SESSION['sort_col']))
44   $_SESSION['sort_col'] = $CONFIG['message_sort_col'];
45 if (!isset($_SESSION['sort_order']))
46   $_SESSION['sort_order'] = $CONFIG['message_sort_order'];
47
48 // set message set for search result
49 if (!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
61 if ($CONFIG['trash_mbox'])
62   $OUTPUT->set_env('trash_mailbox', $CONFIG['trash_mbox']);
63 if ($CONFIG['drafts_mbox'])
64   $OUTPUT->set_env('drafts_mailbox', $CONFIG['drafts_mbox']);
65 if ($CONFIG['junk_mbox'])
66   $OUTPUT->set_env('junk_mailbox', $CONFIG['junk_mbox']);
67
68 if (!$OUTPUT->ajax_call)
69   rcube_add_label('checkingmail', 'deletemessage', 'movemessagetotrash', 'movingmessage');
70
71 // set page title
72 if (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  */
80 function 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  */
303 function 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  */
368 function 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  */
393 function 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  */
416 function 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  */
441 function 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  */
487 function 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  */
525 function 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  */
626 function 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  */
638 function 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  */
700 function 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']) && $ctype_primary == 'multipart' &&
751       !empty($MESSAGE->attachments) && !strstr($message_body, '<html')) {
752     foreach ($MESSAGE->attachments as $attach_prop) {
753       if (strpos($attach_prop->mimetype, 'image/') === 0) {
754         $out .= html::tag('hr') . html::p(array('align' => "center"),
755           html::img(array(
756             'src' => $MESSAGE->get_part_url($attach_prop->mime_id),
757             'title' => $attach_prop->filename,
758             'alt' => $attach_prop->filename,
759           )));
760         }
761     }
762   }
763   
764   // tell client that there are blocked remote objects
765   if ($REMOTE_OBJECTS && !$safe_mode)
766     $OUTPUT->set_env('blockedobjects', true);
767
768   return html::div($attrib, $out);
769   }
770
771
772
773 /**
774  * modify a HTML message that it can be displayed inside a HTML page
775  */
776 function rcmail_html4inline($body, $container_id)
777   {
778   $base_url = "";
779   $last_style_pos = 0;
780   $body_lc = strtolower($body);
781   
782   // check for <base href>
783   if (preg_match(($base_reg = '/(<base.*href=["\']?)([hftps]{3,5}:\/{2}[^"\'\s]+)([^<]*>)/i'), $body, $base_regs))
784     $base_url = $base_regs[2];
785   
786   // find STYLE tags
787   while (($pos = strpos($body_lc, '<style', $last_style_pos)) && ($pos2 = strpos($body_lc, '</style>', $pos)))
788     {
789     $pos = strpos($body_lc, '>', $pos)+1;
790
791     // replace all css definitions with #container [def]
792     $styles = rcmail_mod_css_styles(substr($body, $pos, $pos2-$pos), $container_id, $base_url);
793
794     $body = substr($body, 0, $pos) . $styles . substr($body, $pos2);
795     $body_lc = strtolower($body);
796     $last_style_pos = $pos2;
797     }
798
799   // resolve <base href>
800   if ($base_url)
801     {
802     $body = preg_replace('/(src|background|href)=(["\']?)([\.\/]+[^"\'\s]+)(\2|\s|>)/Uie', "'\\1=\"'.make_absolute_url('\\3', '$base_url').'\"'", $body);
803     $body = preg_replace('/(url\s*\()(["\']?)([\.\/]+[^"\'\)\s]+)(\2)\)/Uie', "'\\1\''.make_absolute_url('\\3', '$base_url').'\')'", $body);
804     $body = preg_replace($base_reg, '', $body);
805     }
806     
807   // modify HTML links to open a new window if clicked
808   $body = preg_replace('/<(a|link)\s+([^>]+)>/Uie', "rcmail_alter_html_link('\\1','\\2', '$container_id');", $body);
809
810   // add comments arround html and other tags
811   $out = preg_replace(array(
812       '/(<!DOCTYPE[^>]*>)/i',
813       '/(<\?xml[^>]*>)/i',
814       '/(<\/?html[^>]*>)/i',
815       '/(<\/?head[^>]*>)/i',
816       '/(<title[^>]*>.*<\/title>)/Ui',
817       '/(<\/?meta[^>]*>)/i'),
818     '<!--\\1-->',
819     $body);
820
821   $out = preg_replace(
822     array('/<body([^>]*)>/i', '/<\/body>/i'),
823     array('<div class="rcmBody"\\1>', '</div>'),
824     $out);
825
826   // quote <? of php and xml files that are specified as text/html
827   $out = preg_replace(array('/<\?/', '/\?>/'), array('&lt;?', '?&gt;'), $out);
828
829   return $out;
830   }
831
832
833 /**
834  * parse link attributes and set correct target
835  */
836 function rcmail_alter_html_link($tag, $attrs, $container_id)
837   {
838   $attrib = parse_attrib_string($attrs);
839
840   if ($tag == 'link' && preg_match('/^https?:\/\//i', $attrib['href']))
841     $attrib['href'] = "./bin/modcss.php?u=" . urlencode($attrib['href']) . "&amp;c=" . urlencode($container_id);
842
843   else if (stristr((string)$attrib['href'], 'mailto:'))
844     $attrib['onclick'] = sprintf(
845       "return %s.command('compose','%s',this)",
846       JS_OBJECT_NAME,
847       JQ(substr($attrib['href'], 7)));
848
849   else if (!empty($attrib['href']) && $attrib['href']{0}!='#')
850     $attrib['target'] = '_blank';
851
852   return "<$tag" . create_attrib_string($attrib, array('href','name','target','onclick','id','class','style','title','rel','type','media')) . ' />';
853   }
854
855
856 /**
857  * decode address string and re-format it as HTML links
858  */
859 function rcmail_address_string($input, $max=NULL, $addicon=NULL)
860   {
861   global $IMAP, $PRINT_MODE, $CONFIG, $OUTPUT, $EMAIL_ADDRESS_PATTERN;
862
863   $a_parts = $IMAP->decode_address_list($input);
864
865   if (!sizeof($a_parts))
866     return $input;
867
868   $c = count($a_parts);
869   $j = 0;
870   $out = '';
871
872   foreach ($a_parts as $part)
873     {
874     $j++;
875     if ($PRINT_MODE)
876       $out .= sprintf('%s &lt;%s&gt;', Q($part['name']), $part['mailto']);
877     else if (preg_match($EMAIL_ADDRESS_PATTERN, $part['mailto']))
878       {
879       $out .= sprintf('<a href="mailto:%s" onclick="return %s.command(\'compose\',\'%s\',this)" class="rcmContactAddress" title="%s">%s</a>',
880                       Q($part['mailto']),
881                       JS_OBJECT_NAME,
882                       JQ($part['mailto']),
883                       Q($part['mailto']),
884                       Q($part['name']));
885                       
886       if ($addicon)
887         $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>',
888                         JS_OBJECT_NAME,
889                         urlencode($part['string']),
890                         rcube_label('addtoaddressbook'),
891                         $CONFIG['skin_path'],
892                         $addicon);
893       }
894     else
895       {
896       if ($part['name'])
897         $out .= Q($part['name']);
898       if ($part['mailto'])
899         $out .= (strlen($out) ? ' ' : '') . sprintf('&lt;%s&gt;', Q($part['mailto']));
900       }
901       
902     if ($c>$j)
903       $out .= ','.($max ? '&nbsp;' : ' ');
904         
905     if ($max && $j==$max && $c>$j)
906       {
907       $out .= '...';
908       break;
909       }        
910     }
911     
912   return $out;
913   }
914
915
916 function rcmail_message_part_controls()
917   {
918   global $MESSAGE;
919   
920   $part = asciiwords(get_input_value('_part', RCUBE_INPUT_GPC));
921   if (!is_object($MESSAGE) || !is_array($MESSAGE->parts) || !($_GET['_uid'] && $_GET['_part']) || !$MESSAGE->mime_parts[$part])
922     return '';
923     
924   $part = $MESSAGE->mime_parts[$part];
925   $table = new html_table(array('cols' => 3));
926   
927   if (!empty($part->filename)) {
928     $table->add('title', Q(rcube_label('filename')));
929     $table->add(null, Q($part->filename));
930     $table->add(null, '[' . html::a('?'.str_replace('_frame=', '_download=', $_SERVER['QUERY_STRING']), Q(rcube_label('download'))) . ']');
931   }
932   
933   if (!empty($part->size)) {
934     $table->add('title', Q(rcube_label('filesize')));
935     $table->add(null, Q(show_bytes($part->size)));
936   }
937   
938   return $table->show($attrib);
939   }
940
941
942
943 function rcmail_message_part_frame($attrib)
944   {
945   global $MESSAGE;
946   
947   $part = $MESSAGE->mime_parts[asciiwords(get_input_value('_part', RCUBE_INPUT_GPC))];
948   $ctype_primary = strtolower($part->ctype_primary);
949
950   $attrib['src'] = Q('./?'.str_replace('_frame=', ($ctype_primary=='text' ? '_show=' : '_preload='), $_SERVER['QUERY_STRING']));
951
952   $attrib_str = create_attrib_string($attrib, array('id', 'class', 'style', 'src', 'width', 'height'));
953   $out = '<iframe '. $attrib_str . "></iframe>";
954     
955   return $out;
956   }
957
958
959 /**
960  * clear message composing settings
961  */
962 function rcmail_compose_cleanup()
963   {
964   if (!isset($_SESSION['compose']))
965     return;
966
967   // remove attachment files from temp dir
968   if (is_array($_SESSION['compose']['attachments']))
969     foreach ($_SESSION['compose']['attachments'] as $attachment)
970       @unlink($attachment['path']);
971   
972   unset($_SESSION['compose']);
973   }
974   
975
976 /**
977  * Send the given message compose object using the configured method
978  */
979 function rcmail_deliver_message(&$message, $from, $mailto)
980 {
981   global $CONFIG;
982
983   $msg_body = $message->get();
984   $headers = $message->headers();
985   
986   // send thru SMTP server using custom SMTP library
987   if ($CONFIG['smtp_server'])
988     {
989     // generate list of recipients
990     $a_recipients = array($mailto);
991   
992     if (strlen($headers['Cc']))
993       $a_recipients[] = $headers['Cc'];
994     if (strlen($headers['Bcc']))
995       $a_recipients[] = $headers['Bcc'];
996   
997     // clean Bcc from header for recipients
998     $send_headers = $headers;
999     unset($send_headers['Bcc']);
1000     // here too, it because txtHeaders() below use $message->_headers not only $send_headers
1001     unset($message->_headers['Bcc']);
1002
1003     // send message
1004     $smtp_response = array();
1005     $sent = smtp_mail($from, $a_recipients, ($foo = $message->txtHeaders($send_headers, true)), $msg_body, $smtp_response);
1006
1007     // log error
1008     if (!$sent)
1009       raise_error(array('code' => 800, 'type' => 'smtp', 'line' => __LINE__, 'file' => __FILE__,
1010                         'message' => "SMTP error: ".join("\n", $smtp_response)), TRUE, FALSE);
1011     }
1012   
1013   // send mail using PHP's mail() function
1014   else
1015     {
1016     // unset some headers because they will be added by the mail() function
1017     $headers_enc = $message->headers($headers);
1018     $headers_php = $message->_headers;
1019     unset($headers_php['To'], $headers_php['Subject']);
1020     
1021     // reset stored headers and overwrite
1022     $message->_headers = array();
1023     $header_str = $message->txtHeaders($headers_php);
1024   
1025     if (ini_get('safe_mode'))
1026       $sent = mail($headers_enc['To'], $headers_enc['Subject'], $msg_body, $header_str);
1027     else
1028       $sent = mail($headers_enc['To'], $headers_enc['Subject'], $msg_body, $header_str, "-f$from");
1029     }
1030   
1031   if ($sent)  // remove MDN headers after sending
1032     unset($headers['Return-Receipt-To'], $headers['Disposition-Notification-To']);
1033   
1034   $message->_headers = array();
1035   $message->headers($headers);
1036   
1037   return $sent;
1038 }
1039
1040
1041 function rcmail_send_mdn($uid)
1042 {
1043   global $CONFIG, $USER, $IMAP;
1044
1045   $message = new rcube_message($uid);
1046   
1047   if ($message->headers->mdn_to && !$message->headers->mdn_sent)
1048   {
1049     $identity = $USER->get_identity();
1050     $sender = format_email_recipient($identity['email'], $identity['name']);
1051     $recipient = array_shift($IMAP->decode_address_list($message->headers->mdn_to));
1052     $mailto = $recipient['mailto'];
1053
1054     $compose = new rcube_mail_mime(rcmail_header_delm());
1055     $compose->setParam(array(
1056       'text_encoding' => 'quoted-printable',
1057       'html_encoding' => 'quoted-printable',
1058       'head_encoding' => 'quoted-printable',
1059       'head_charset'  => RCMAIL_CHARSET,
1060       'html_charset'  => RCMAIL_CHARSET,
1061       'text_charset'  => RCMAIL_CHARSET,
1062     ));
1063     
1064     // compose headers array
1065     $headers = array(
1066       'Date' => date('r'),
1067       'From' => $sender,
1068       'To'   => $message->headers->mdn_to,
1069       'Subject' => rcube_label('receiptread') . ': ' . $message->subject,
1070       'Message-ID' => sprintf('<%s@%s>', md5(uniqid('rcmail'.rand(),true)), rcmail_mail_domain($_SESSION['imap_host'])),
1071       'X-Sender' => $identity['email'],
1072       'Content-Type' => 'multipart/report; report-type=disposition-notification',
1073     );
1074     
1075     if (!empty($CONFIG['useragent']))
1076       $headers['User-Agent'] = $CONFIG['useragent'];
1077
1078     $body = rcube_label("yourmessage") . "\r\n\r\n" .
1079       "\t" . rcube_label("to") . ': ' . rcube_imap::decode_mime_string($message->headers->to, $message->headers->charset) . "\r\n" .
1080       "\t" . rcube_label("subject") . ': ' . $message->subject . "\r\n" .
1081       "\t" . rcube_label("sent") . ': ' . format_date($message->headers->date, $CONFIG['date_long']) . "\r\n" .
1082       "\r\n" . rcube_label("receiptnote") . "\r\n";
1083     
1084     $ua = !empty($CONFIG['useragent']) ? $CONFIG['useragent'] : "RoundCube Webmail (Version ".RCMAIL_VERSION.")";
1085     $report = "Reporting-UA: $ua\r\n";
1086     
1087     if ($message->headers->to)
1088         $report .= "Original-Recipient: {$message->headers->to}\r\n";
1089     
1090     $report .= "Final-Recipient: rfc822; {$identity['email']}\r\n" .
1091                "Original-Message-ID: {$message->headers->messageID}\r\n" .
1092                "Disposition: manual-action/MDN-sent-manually; displayed\r\n";
1093     
1094     $compose->headers($headers);
1095     $compose->setTXTBody(wordwrap($body, 75, "\r\n"));
1096     $compose->addAttachment($report, 'message/disposition-notification', 'MDNPart2.txt', false, '7bit', 'inline');
1097
1098     $sent = rcmail_deliver_message($compose, $identity['email'], $mailto);
1099
1100     if ($sent)
1101     {
1102       $IMAP->set_flag($message->uid, 'MDNSENT');
1103       return true;
1104     }
1105   }
1106   
1107   return false;
1108 }
1109
1110
1111 // register UI objects
1112 $OUTPUT->add_handlers(array(
1113   'mailboxlist' => 'rcmail_mailbox_list',
1114   'messages' => 'rcmail_message_list',
1115   'messagecountdisplay' => 'rcmail_messagecount_display',
1116   'quotadisplay' => 'rcmail_quota_display',
1117   'messageheaders' => 'rcmail_message_headers',
1118   'messagebody' => 'rcmail_message_body',
1119   'messagecontentframe' => 'rcmail_messagecontent_frame',
1120   'messagepartframe' => 'rcmail_message_part_frame',
1121   'messagepartcontrols' => 'rcmail_message_part_controls',
1122   'searchform' => array($OUTPUT, 'search_form'),
1123 ));
1124
1125 ?>