]> git.donarmstrong.com Git - roundcube.git/blob - program/steps/mail/compose.inc
Imported Upstream version 0.7
[roundcube.git] / program / steps / mail / compose.inc
1 <?php
2
3 /*
4  +-----------------------------------------------------------------------+
5  | program/steps/mail/compose.inc                                        |
6  |                                                                       |
7  | This file is part of the Roundcube Webmail client                     |
8  | Copyright (C) 2005-2011, The Roundcube Dev Team                       |
9  | Licensed under the GNU GPL                                            |
10  |                                                                       |
11  | PURPOSE:                                                              |
12  |   Compose a new mail message with all headers and attachments         |
13  |                                                                       |
14  +-----------------------------------------------------------------------+
15  | Author: Thomas Bruederli <roundcube@gmail.com>                        |
16  +-----------------------------------------------------------------------+
17
18  $Id: compose.inc 5545 2011-12-05 12:59:21Z thomasb $
19
20 */
21
22 // define constants for message compose mode
23 define('RCUBE_COMPOSE_REPLY', 0x0106);
24 define('RCUBE_COMPOSE_FORWARD', 0x0107);
25 define('RCUBE_COMPOSE_DRAFT', 0x0108);
26 define('RCUBE_COMPOSE_EDIT', 0x0109);
27
28 $MESSAGE_FORM = null;
29 $MESSAGE      = null;
30 $COMPOSE_ID   = get_input_value('_id', RCUBE_INPUT_GET);
31 $COMPOSE      = null;
32
33 if ($COMPOSE_ID && $_SESSION['compose_data_'.$COMPOSE_ID])
34   $COMPOSE =& $_SESSION['compose_data_'.$COMPOSE_ID];
35
36 // give replicated session storage some time to synchronize
37 $retries = 0;
38 while ($COMPOSE_ID && !is_array($COMPOSE) && $RCMAIL->db->is_replicated() && $retries++ < 5) {
39   usleep(500000);
40   $RCMAIL->session->reload();
41   if ($_SESSION['compose_data_'.$COMPOSE_ID])
42     $COMPOSE =& $_SESSION['compose_data_'.$COMPOSE_ID];
43 }
44
45 // Nothing below is called during message composition, only at "new/forward/reply/draft" initialization or
46 // if a compose-ID is given (i.e. when the compose step is opened in a new window/tab).
47 if (!is_array($COMPOSE))
48 {
49   // Infinite redirect prevention in case of broken session (#1487028)
50   if ($COMPOSE_ID)
51     raise_error(array('code' => 500, 'type' => 'php',
52       'file' => __FILE__, 'line' => __LINE__,
53       'message' => "Invalid compose ID"), true, true);
54
55   $COMPOSE_ID = uniqid(mt_rand());
56   $_SESSION['compose_data_'.$COMPOSE_ID] = array(
57     'id'      => $COMPOSE_ID,
58     'param'   => request2param(RCUBE_INPUT_GET),
59     'mailbox' => $IMAP->get_mailbox_name(),
60   );
61   $COMPOSE =& $_SESSION['compose_data_'.$COMPOSE_ID];
62
63   // process values like "mailto:foo@bar.com?subject=new+message&cc=another"
64   if ($COMPOSE['param']['to']) {
65     // #1486037: remove "mailto:" prefix
66     $COMPOSE['param']['to'] = preg_replace('/^mailto:/i', '', $COMPOSE['param']['to']);
67     $mailto = explode('?', $COMPOSE['param']['to']);
68     if (count($mailto) > 1) {
69       $COMPOSE['param']['to'] = $mailto[0];
70       parse_str($mailto[1], $query);
71       foreach ($query as $f => $val)
72         $COMPOSE['param'][$f] = $val;
73     }
74   }
75
76   // select folder where to save the sent message
77   $COMPOSE['param']['sent_mbox'] = $RCMAIL->config->get('sent_mbox');
78
79   // pipe compose parameters thru plugins
80   $plugin = $RCMAIL->plugins->exec_hook('message_compose', $COMPOSE);
81   $COMPOSE['param'] = array_merge($COMPOSE['param'], $plugin['param']);
82
83   // add attachments listed by message_compose hook
84   if (is_array($plugin['attachments'])) {
85     foreach ($plugin['attachments'] as $attach) {
86       // we have structured data
87       if (is_array($attach)) {
88         $attachment = $attach;
89       }
90       // only a file path is given
91       else {
92         $filename = basename($attach);
93         $attachment = array(
94           'group' => $COMPOSE_ID,
95           'name' => $filename,
96           'mimetype' => rc_mime_content_type($attach, $filename),
97           'path' => $attach,
98         );
99       }
100
101       // save attachment if valid
102       if (($attachment['data'] && $attachment['name']) || ($attachment['path'] && file_exists($attachment['path']))) {
103         $attachment = rcmail::get_instance()->plugins->exec_hook('attachment_save', $attachment);
104       }
105
106       if ($attachment['status'] && !$attachment['abort']) {
107         unset($attachment['data'], $attachment['status'], $attachment['abort']);
108         $COMPOSE['attachments'][$attachment['id']] = $attachment;
109       }
110     }
111   }
112
113   // check if folder for saving sent messages exists and is subscribed (#1486802)
114   if ($sent_folder = $COMPOSE['param']['sent_mbox']) {
115     rcmail_check_sent_folder($sent_folder, true);
116   }
117
118   // redirect to a unique URL with all parameters stored in session
119   $OUTPUT->redirect(array('_action' => 'compose', '_id' => $COMPOSE['id']));
120 }
121
122
123 // add some labels to client
124 $OUTPUT->add_label('nosubject', 'nosenderwarning', 'norecipientwarning', 'nosubjectwarning', 'cancel',
125     'nobodywarning', 'notsentwarning', 'notuploadedwarning', 'savingmessage', 'sendingmessage', 
126     'messagesaved', 'converting', 'editorwarning', 'searching', 'uploading', 'uploadingmany',
127     'fileuploaderror', 'sendmessage');
128
129 $OUTPUT->set_env('compose_id', $COMPOSE['id']);
130
131 // add config parameters to client script
132 if (!empty($CONFIG['drafts_mbox'])) {
133   $OUTPUT->set_env('drafts_mailbox', $CONFIG['drafts_mbox']);
134   $OUTPUT->set_env('draft_autosave', $CONFIG['draft_autosave']);
135 }
136 // set current mailbox in client environment
137 $OUTPUT->set_env('mailbox', $IMAP->get_mailbox_name());
138 $OUTPUT->set_env('sig_above', $RCMAIL->config->get('sig_above', false));
139 $OUTPUT->set_env('top_posting', $RCMAIL->config->get('top_posting', false));
140 $OUTPUT->set_env('recipients_separator', trim($RCMAIL->config->get('recipients_separator', ',')));
141
142 // use jquery UI for showing prompt() dialogs
143 $RCMAIL->plugins->load_plugin('jqueryui');
144
145 // get reference message and set compose mode
146 if ($msg_uid = $COMPOSE['param']['draft_uid']) {
147   $RCMAIL->imap->set_mailbox($CONFIG['drafts_mbox']);
148   $compose_mode = RCUBE_COMPOSE_DRAFT;
149 }
150 else if ($msg_uid = $COMPOSE['param']['reply_uid'])
151   $compose_mode = RCUBE_COMPOSE_REPLY;
152 else if ($msg_uid = $COMPOSE['param']['forward_uid'])
153   $compose_mode = RCUBE_COMPOSE_FORWARD;
154 else if ($msg_uid = $COMPOSE['param']['uid'])
155   $compose_mode = RCUBE_COMPOSE_EDIT;
156
157 $config_show_sig = $RCMAIL->config->get('show_sig', 1);
158 if ($config_show_sig == 1)
159   $OUTPUT->set_env('show_sig', true);
160 else if ($config_show_sig == 2 && (empty($compose_mode) || $compose_mode == RCUBE_COMPOSE_EDIT || $compose_mode == RCUBE_COMPOSE_DRAFT))
161   $OUTPUT->set_env('show_sig', true);
162 else if ($config_show_sig == 3 && ($compose_mode == RCUBE_COMPOSE_REPLY || $compose_mode == RCUBE_COMPOSE_FORWARD))
163   $OUTPUT->set_env('show_sig', true);
164 else
165   $OUTPUT->set_env('show_sig', false);
166
167 // set line length for body wrapping
168 $LINE_LENGTH = $RCMAIL->config->get('line_length', 72);
169
170 if (!empty($msg_uid))
171 {
172   // similar as in program/steps/mail/show.inc
173   // re-set 'prefer_html' to have possibility to use html part for compose
174   $CONFIG['prefer_html'] = $CONFIG['prefer_html'] || $CONFIG['htmleditor'] || $compose_mode == RCUBE_COMPOSE_DRAFT || $compose_mode == RCUBE_COMPOSE_EDIT;
175   $MESSAGE = new rcube_message($msg_uid);
176
177   // make sure message is marked as read
178   if ($MESSAGE && $MESSAGE->headers && empty($MESSAGE->headers->flags['SEEN']))
179     $IMAP->set_flag($msg_uid, 'SEEN');
180
181   if (!empty($MESSAGE->headers->charset))
182     $IMAP->set_charset($MESSAGE->headers->charset);
183
184   if ($compose_mode == RCUBE_COMPOSE_REPLY)
185   {
186     $COMPOSE['reply_uid'] = $msg_uid;
187     $COMPOSE['reply_msgid'] = $MESSAGE->headers->messageID;
188     $COMPOSE['references']  = trim($MESSAGE->headers->references . " " . $MESSAGE->headers->messageID);
189
190     if (!empty($COMPOSE['param']['all']))
191       $MESSAGE->reply_all = $COMPOSE['param']['all'];
192
193     $OUTPUT->set_env('compose_mode', 'reply');
194
195     // Save the sent message in the same folder of the message being replied to
196     if ($RCMAIL->config->get('reply_same_folder') && ($sent_folder = $COMPOSE['mailbox'])
197       && rcmail_check_sent_folder($sent_folder, false)
198     ) {
199       $COMPOSE['param']['sent_mbox'] = $sent_folder;
200     }
201   }
202   else if ($compose_mode == RCUBE_COMPOSE_DRAFT)
203   {
204     if ($MESSAGE->headers->others['x-draft-info'])
205     {
206       // get reply_uid/forward_uid to flag the original message when sending
207       $info = rcmail_draftinfo_decode($MESSAGE->headers->others['x-draft-info']);
208
209       if ($info['type'] == 'reply')
210         $COMPOSE['reply_uid'] = $info['uid'];
211       else if ($info['type'] == 'forward')
212         $COMPOSE['forward_uid'] = $info['uid'];
213
214       $COMPOSE['mailbox'] = $info['folder'];
215
216       // Save the sent message in the same folder of the message being replied to
217       if ($RCMAIL->config->get('reply_same_folder') && ($sent_folder = $info['folder'])
218         && rcmail_check_sent_folder($sent_folder, false)
219       ) {
220         $COMPOSE['param']['sent_mbox'] = $sent_folder;
221       }
222     }
223
224     if ($MESSAGE->headers->in_reply_to)
225       $COMPOSE['reply_msgid'] = '<'.$MESSAGE->headers->in_reply_to.'>';
226
227     $COMPOSE['references']  = $MESSAGE->headers->references;
228   }
229   else if ($compose_mode == RCUBE_COMPOSE_FORWARD)
230   {
231     $COMPOSE['forward_uid'] = $msg_uid;
232     $OUTPUT->set_env('compose_mode', 'forward');
233
234     if (!empty($COMPOSE['param']['attachment']))
235       $MESSAGE->forward_attachment = true;
236   }
237 }
238
239 $MESSAGE->compose = array();
240
241 // get user's identities
242 $MESSAGE->identities = $USER->list_identities();
243 if (count($MESSAGE->identities))
244 {
245   foreach ($MESSAGE->identities as $idx => $ident) {
246     $email = mb_strtolower(rcube_idn_to_utf8($ident['email']));
247
248     $MESSAGE->identities[$idx]['email_ascii'] = $ident['email'];
249     $MESSAGE->identities[$idx]['ident']       = format_email_recipient($ident['email'], $ident['name']);
250     $MESSAGE->identities[$idx]['email']       = $email;
251   }
252 }
253
254 // Set From field value
255 if (!empty($_POST['_from'])) {
256   $MESSAGE->compose['from'] = get_input_value('_from', RCUBE_INPUT_POST);
257 }
258 else if (!empty($COMPOSE['param']['from'])) {
259   $MESSAGE->compose['from'] = $COMPOSE['param']['from'];
260 }
261 else if (count($MESSAGE->identities)) {
262   $a_recipients = array();
263   $a_names      = array();
264
265   // extract all recipients of the reply-message
266   if (is_object($MESSAGE->headers) && in_array($compose_mode, array(RCUBE_COMPOSE_REPLY, RCUBE_COMPOSE_FORWARD)))
267   {
268     $a_to = $IMAP->decode_address_list($MESSAGE->headers->to);
269     foreach ($a_to as $addr) {
270       if (!empty($addr['mailto'])) {
271         $a_recipients[] = strtolower($addr['mailto']);
272         $a_names[]      = $addr['name'];
273       }
274     }
275
276     if (!empty($MESSAGE->headers->cc)) {
277       $a_cc = $IMAP->decode_address_list($MESSAGE->headers->cc);
278       foreach ($a_cc as $addr) {
279         if (!empty($addr['mailto'])) {
280           $a_recipients[] = strtolower($addr['mailto']);
281           $a_names[]      = $addr['name'];
282         }
283       }
284     }
285   }
286
287   $from_idx         = null;
288   $default_identity = null;
289   $return_path      = $MESSAGE->headers->others['return-path'];
290
291   // Select identity
292   foreach ($MESSAGE->identities as $idx => $ident) {
293     // save default identity ID
294     if ($ident['standard']) {
295       $default_identity = $idx;
296     }
297
298     // use From header
299     if (in_array($compose_mode, array(RCUBE_COMPOSE_DRAFT, RCUBE_COMPOSE_EDIT))) {
300       if ($MESSAGE->headers->from == $ident['ident']) {
301         $from_idx = $idx;
302         break;
303       }
304     }
305     // reply to yourself
306     else if ($compose_mode == RCUBE_COMPOSE_REPLY && $MESSAGE->headers->from == $ident['ident']) {
307       $from_idx = $idx;
308       break;
309     }
310     // use replied message recipients
311     else if (($found = array_search($ident['email_ascii'], $a_recipients)) !== false) {
312       // match identity name, prefer default identity
313       if ($from_idx === null || ($a_names[$found] && $ident['name'] && $a_names[$found] == $ident['name'])) {
314         $from_idx = $idx;
315       }
316     }
317   }
318
319   // Fallback using Return-Path
320   if ($from_idx === null && $return_path) {
321     foreach ($MESSAGE->identities as $idx => $ident) {
322       if (strpos($return_path, str_replace('@', '=', $ident['email_ascii']).'@') !== false) {
323         $from_idx = $idx;
324         break;
325       }
326     }
327   }
328
329   // Still no ID, use default/first identity
330   if ($from_idx === null) {
331     $from_idx = $default_identity !== null ? $default_identity : key(reset($MESSAGE->identities));
332   }
333
334   $ident   = $MESSAGE->identities[$from_idx];
335   $from_id = $ident['identity_id'];
336
337   $MESSAGE->compose['from_email'] = $ident['email'];
338   $MESSAGE->compose['from']       = $from_id;
339 }
340
341 // Set other headers
342 $a_recipients = array();
343 $parts        = array('to', 'cc', 'bcc', 'replyto', 'followupto');
344 $separator    = trim($RCMAIL->config->get('recipients_separator', ',')) . ' ';
345
346 foreach ($parts as $header) {
347   $fvalue = '';
348   $decode_header = true;
349
350   // we have a set of recipients stored is session
351   if ($header == 'to' && ($mailto_id = $COMPOSE['param']['mailto'])
352       && $_SESSION['mailto'][$mailto_id]
353   ) {
354     $fvalue = urldecode($_SESSION['mailto'][$mailto_id]);
355     $decode_header = false;
356
357     // make session to not grow up too much
358     unset($_SESSION['mailto'][$mailto_id]);
359     $COMPOSE['param']['to'] = $fvalue;
360   }
361   else if (!empty($_POST['_'.$header])) {
362     $fvalue = get_input_value('_'.$header, RCUBE_INPUT_POST, TRUE);
363   }
364   else if (!empty($COMPOSE['param'][$header])) {
365     $fvalue = $COMPOSE['param'][$header];
366   }
367   else if ($compose_mode == RCUBE_COMPOSE_REPLY) {
368     // get recipent address(es) out of the message headers
369     if ($header == 'to') {
370       $mailfollowup = $MESSAGE->headers->others['mail-followup-to'];
371       $mailreplyto  = $MESSAGE->headers->others['mail-reply-to'];
372
373       // Reply to mailing list...
374       if ($MESSAGE->reply_all == 'list' && $mailfollowup)
375         $fvalue = $mailfollowup;
376       else if ($MESSAGE->reply_all == 'list'
377         && preg_match('/<mailto:([^>]+)>/i', $MESSAGE->headers->others['list-post'], $m))
378         $fvalue = $m[1];
379       // Reply to...
380       else if ($MESSAGE->reply_all && $mailfollowup)
381         $fvalue = $mailfollowup;
382       else if ($mailreplyto)
383         $fvalue = $mailreplyto;
384       else if (!empty($MESSAGE->headers->replyto))
385         $fvalue = $MESSAGE->headers->replyto;
386       else if (!empty($MESSAGE->headers->from))
387         $fvalue = $MESSAGE->headers->from;
388
389       // Reply to message sent by yourself (#1487074)
390       if (!empty($ident) && $fvalue == $ident['ident']) {
391         $fvalue = $MESSAGE->headers->to;
392       }
393     }
394     // add recipient of original message if reply to all
395     else if ($header == 'cc' && !empty($MESSAGE->reply_all) && $MESSAGE->reply_all != 'list') {
396       if ($v = $MESSAGE->headers->to)
397         $fvalue .= $v;
398       if ($v = $MESSAGE->headers->cc)
399         $fvalue .= (!empty($fvalue) ? $separator : '') . $v;
400     }
401   }
402   else if (in_array($compose_mode, array(RCUBE_COMPOSE_DRAFT, RCUBE_COMPOSE_EDIT))) {
403     // get drafted headers
404     if ($header=='to' && !empty($MESSAGE->headers->to))
405       $fvalue = $MESSAGE->get_header('to');
406     else if ($header=='cc' && !empty($MESSAGE->headers->cc))
407       $fvalue = $MESSAGE->get_header('cc');
408     else if ($header=='bcc' && !empty($MESSAGE->headers->bcc))
409       $fvalue = $MESSAGE->get_header('bcc');
410     else if ($header=='replyto' && !empty($MESSAGE->headers->others['mail-reply-to']))
411       $fvalue = $MESSAGE->get_header('mail-reply-to');
412     else if ($header=='replyto' && !empty($MESSAGE->headers->replyto))
413       $fvalue = $MESSAGE->get_header('reply-to');
414     else if ($header=='followupto' && !empty($MESSAGE->headers->others['mail-followup-to']))
415       $fvalue = $MESSAGE->get_header('mail-followup-to');
416   }
417
418   // split recipients and put them back together in a unique way
419   if (!empty($fvalue) && in_array($header, array('to', 'cc', 'bcc'))) {
420     $to_addresses = $IMAP->decode_address_list($fvalue, null, $decode_header);
421     $fvalue = array();
422
423     foreach ($to_addresses as $addr_part) {
424       if (empty($addr_part['mailto']))
425         continue;
426
427       $mailto = mb_strtolower(rcube_idn_to_utf8($addr_part['mailto']));
428
429       if (!in_array($mailto, $a_recipients)
430         && ($header == 'to' || empty($MESSAGE->compose['from_email']) || $mailto != $MESSAGE->compose['from_email'])
431       ) {
432         if ($addr_part['name'] && $addr_part['mailto'] != $addr_part['name'])
433           $string = format_email_recipient($mailto, $addr_part['name']);
434         else
435           $string = $mailto;
436
437         $fvalue[] = $string;
438         $a_recipients[] = $addr_part['mailto'];
439       }
440     }
441
442     $fvalue = implode($separator, $fvalue);
443   }
444
445   $MESSAGE->compose[$header] = $fvalue;
446 }
447 unset($a_recipients);
448
449 // process $MESSAGE body/attachments, set $MESSAGE_BODY/$HTML_MODE vars and some session data
450 $MESSAGE_BODY = rcmail_prepare_message_body();
451
452
453 /****** compose mode functions ********/
454
455 function rcmail_compose_headers($attrib)
456 {
457   global $MESSAGE;
458
459   list($form_start, $form_end) = get_form_tags($attrib);
460
461   $out  = '';
462   $part = strtolower($attrib['part']);
463
464   switch ($part)
465   {
466     case 'from':
467       return $form_start . rcmail_compose_header_from($attrib);
468
469     case 'to':
470     case 'cc':
471     case 'bcc':
472       $fname = '_' . $part;
473       $header = $param = $part;
474
475       $allow_attrib = array('id', 'class', 'style', 'cols', 'rows', 'tabindex');
476       $field_type = 'html_textarea';
477       break;
478
479     case 'replyto':
480     case 'reply-to':
481       $fname = '_replyto';
482       $param = 'replyto';
483       $header = 'reply-to';
484
485     case 'followupto':
486     case 'followup-to':
487       if (!$fname) {
488         $fname = '_followupto';
489         $param = 'followupto';
490         $header = 'mail-followup-to';
491       }
492
493       $allow_attrib = array('id', 'class', 'style', 'size', 'tabindex');
494       $field_type = 'html_inputfield';
495       break;
496   }
497
498   if ($fname && $field_type)
499   {
500     // pass the following attributes to the form class
501     $field_attrib = array('name' => $fname, 'spellcheck' => 'false');
502     foreach ($attrib as $attr => $value)
503       if (in_array($attr, $allow_attrib))
504         $field_attrib[$attr] = $value;
505
506     // create teaxtarea object
507     $input = new $field_type($field_attrib);
508     $out = $input->show($MESSAGE->compose[$param]);
509   }
510
511   if ($form_start)
512     $out = $form_start.$out;
513
514   // configure autocompletion
515   rcube_autocomplete_init();
516
517   return $out;
518 }
519
520
521 function rcmail_compose_header_from($attrib)
522 {
523   global $MESSAGE, $OUTPUT;
524
525   // pass the following attributes to the form class
526   $field_attrib = array('name' => '_from');
527   foreach ($attrib as $attr => $value)
528     if (in_array($attr, array('id', 'class', 'style', 'size', 'tabindex')))
529       $field_attrib[$attr] = $value;
530
531   if (count($MESSAGE->identities))
532   {
533     $a_signatures = array();
534
535     $field_attrib['onchange'] = JS_OBJECT_NAME.".change_identity(this)";
536     $select_from = new html_select($field_attrib);
537
538     // create SELECT element
539     foreach ($MESSAGE->identities as $sql_arr)
540     {
541       $identity_id = $sql_arr['identity_id'];
542       $select_from->add(format_email_recipient($sql_arr['email'], $sql_arr['name']), $identity_id);
543
544       // add signature to array
545       if (!empty($sql_arr['signature']) && empty($COMPOSE['param']['nosig']))
546       {
547         $a_signatures[$identity_id]['text'] = $sql_arr['signature'];
548         $a_signatures[$identity_id]['is_html'] = ($sql_arr['html_signature'] == 1) ? true : false;
549         if ($a_signatures[$identity_id]['is_html'])
550         {
551             $h2t = new html2text($a_signatures[$identity_id]['text'], false, false);
552             $a_signatures[$identity_id]['plain_text'] = trim($h2t->get_text());
553         }
554       }
555     }
556
557     $out = $select_from->show($MESSAGE->compose['from']);
558
559     // add signatures to client
560     $OUTPUT->set_env('signatures', $a_signatures);
561   }
562   // no identities, display text input field
563   else {
564     $field_attrib['class'] = 'from_address';
565     $input_from = new html_inputfield($field_attrib);
566     $out = $input_from->show($MESSAGE->compose['from']);
567   }
568
569   return $out;
570 }
571
572
573 function rcmail_compose_editor_mode()
574 {
575   global $RCMAIL, $MESSAGE, $compose_mode;
576   static $useHtml;
577
578   if ($useHtml !== null)
579     return $useHtml;
580
581   $html_editor = intval($RCMAIL->config->get('htmleditor'));
582
583   if ($compose_mode == RCUBE_COMPOSE_DRAFT || $compose_mode == RCUBE_COMPOSE_EDIT) {
584     $useHtml = $MESSAGE->has_html_part();
585   }
586   else if ($compose_mode == RCUBE_COMPOSE_REPLY) {
587     $useHtml = ($html_editor == 1 || ($html_editor == 2 && $MESSAGE->has_html_part()));
588   }
589   else { // RCUBE_COMPOSE_FORWARD or NEW
590     $useHtml = ($html_editor == 1);
591   }
592
593   return $useHtml;
594 }
595
596
597 function rcmail_prepare_message_body()
598 {
599   global $RCMAIL, $MESSAGE, $COMPOSE, $compose_mode, $LINE_LENGTH, $HTML_MODE;
600
601   // use posted message body
602   if (!empty($_POST['_message'])) {
603     $body = get_input_value('_message', RCUBE_INPUT_POST, true);
604     $isHtml = (bool) get_input_value('_is_html', RCUBE_INPUT_POST);
605   }
606   else if ($COMPOSE['param']['body']) {
607     $body = $COMPOSE['param']['body'];
608     $isHtml = false;
609   }
610   // forward as attachment
611   else if ($compose_mode == RCUBE_COMPOSE_FORWARD && $MESSAGE->forward_attachment) {
612     $isHtml = rcmail_compose_editor_mode();
613     $body = '';
614     if (empty($COMPOSE['attachments']))
615       rcmail_write_forward_attachment($MESSAGE);
616   }
617   // reply/edit/draft/forward
618   else if ($compose_mode) {
619     $has_html_part = $MESSAGE->has_html_part();
620     $isHtml = rcmail_compose_editor_mode();
621
622     if ($isHtml) {
623       if ($has_html_part) {
624         $body = $MESSAGE->first_html_part();
625       }
626       else {
627         $body = $MESSAGE->first_text_part();
628         // try to remove the signature
629         if ($RCMAIL->config->get('strip_existing_sig', true))
630           $body = rcmail_remove_signature($body);
631         // add HTML formatting
632         $body = rcmail_plain_body($body);
633         if ($body)
634           $body = '<pre>' . $body . '</pre>';
635       }
636     }
637     else {
638       if ($has_html_part) {
639         // use html part if it has been used for message (pre)viewing
640         // decrease line length for quoting
641         $len = $compose_mode == RCUBE_COMPOSE_REPLY ? $LINE_LENGTH-2 : $LINE_LENGTH;
642         $txt = new html2text($MESSAGE->first_html_part(), false, true, $len);
643         $body = $txt->get_text();
644       }
645       else {
646         $body = $MESSAGE->first_text_part($part);
647         if ($body && $part && $part->ctype_secondary == 'plain'
648             && $part->ctype_parameters['format'] == 'flowed'
649         ) {
650           $body = rcube_message::unfold_flowed($body);
651         }
652       }
653     }
654
655     // compose reply-body
656     if ($compose_mode == RCUBE_COMPOSE_REPLY)
657       $body = rcmail_create_reply_body($body, $isHtml);
658     // forward message body inline
659     else if ($compose_mode == RCUBE_COMPOSE_FORWARD)
660       $body = rcmail_create_forward_body($body, $isHtml);
661     // load draft message body
662     else if ($compose_mode == RCUBE_COMPOSE_DRAFT || $compose_mode == RCUBE_COMPOSE_EDIT)
663       $body = rcmail_create_draft_body($body, $isHtml);
664   }
665   else { // new message
666     $isHtml = rcmail_compose_editor_mode();
667   }
668
669   $plugin = $RCMAIL->plugins->exec_hook('message_compose_body',
670     array('body' => $body, 'html' => $isHtml, 'mode' => $compose_mode));
671   $body = $plugin['body'];
672   unset($plugin);
673
674   // add blocked.gif attachment (#1486516)
675   if ($isHtml && preg_match('#<img src="\./program/blocked\.gif"#', $body)) {
676     if ($attachment = rcmail_save_image('program/blocked.gif', 'image/gif')) {
677       $COMPOSE['attachments'][$attachment['id']] = $attachment;
678       $body = preg_replace('#\./program/blocked\.gif#',
679         $RCMAIL->comm_path.'&_action=display-attachment&_file=rcmfile'.$attachment['id'].'&_id='.$COMPOSE['id'],
680         $body);
681     }
682   }
683
684   $HTML_MODE = $isHtml;
685
686   return $body;
687 }
688
689 function rcmail_compose_body($attrib)
690 {
691   global $RCMAIL, $CONFIG, $OUTPUT, $MESSAGE, $compose_mode, $LINE_LENGTH, $HTML_MODE, $MESSAGE_BODY;
692
693   list($form_start, $form_end) = get_form_tags($attrib);
694   unset($attrib['form']);
695
696   if (empty($attrib['id']))
697     $attrib['id'] = 'rcmComposeBody';
698
699   $attrib['name'] = '_message';
700
701   $isHtml = $HTML_MODE;
702
703   $out = $form_start ? "$form_start\n" : '';
704
705   $saveid = new html_hiddenfield(array('name' => '_draft_saveid', 'value' => $compose_mode==RCUBE_COMPOSE_DRAFT ? str_replace(array('<','>'), "", $MESSAGE->headers->messageID) : ''));
706   $out .= $saveid->show();
707
708   $drafttoggle = new html_hiddenfield(array('name' => '_draft', 'value' => 'yes'));
709   $out .= $drafttoggle->show();
710
711   $msgtype = new html_hiddenfield(array('name' => '_is_html', 'value' => ($isHtml?"1":"0")));
712   $out .= $msgtype->show();
713
714   // If desired, set this textarea to be editable by TinyMCE
715   if ($isHtml) {
716     $attrib['class'] = 'mce_editor';
717     $textarea = new html_textarea($attrib);
718     $out .= $textarea->show($MESSAGE_BODY);
719   }
720   else {
721     $textarea = new html_textarea($attrib);
722     $out .= $textarea->show('');
723     // quote plain text, inject into textarea
724     $table = get_html_translation_table(HTML_SPECIALCHARS);
725     $MESSAGE_BODY = strtr($MESSAGE_BODY, $table);
726     $out = substr($out, 0, -11) . $MESSAGE_BODY . '</textarea>';
727   }
728
729   $out .= $form_end ? "\n$form_end" : '';
730
731   $OUTPUT->set_env('composebody', $attrib['id']);
732
733   // include HTML editor
734   rcube_html_editor();
735
736   // include GoogieSpell
737   if (!empty($CONFIG['enable_spellcheck'])) {
738     $engine           = $RCMAIL->config->get('spellcheck_engine','googie');
739     $dictionary       = (bool) $RCMAIL->config->get('spellcheck_dictionary');
740     $spellcheck_langs = (array) $RCMAIL->config->get('spellcheck_languages',
741       array('da'=>'Dansk', 'de'=>'Deutsch', 'en' => 'English', 'es'=>'Español',
742             'fr'=>'Français', 'it'=>'Italiano', 'nl'=>'Nederlands', 'pl'=>'Polski',
743             'pt'=>'Português', 'fi'=>'Suomi', 'sv'=>'Svenska'));
744
745     // googie works only with two-letter codes
746     if ($engine == 'googie') {
747       $lang = strtolower(substr($_SESSION['language'], 0, 2));
748
749       $spellcheck_langs_googie = array();
750       foreach ($spellcheck_langs as $key => $name)
751         $spellcheck_langs_googie[strtolower(substr($key,0,2))] = $name;
752         $spellcheck_langs = $spellcheck_langs_googie;
753     }
754     else {
755       $lang = $_SESSION['language'];
756
757       // if not found in the list, try with two-letter code
758       if (!$spellcheck_langs[$lang])
759         $lang = strtolower(substr($lang, 0, 2));
760     }
761
762     if (!$spellcheck_langs[$lang])
763       $lang = 'en';
764
765     $editor_lang_set = array();
766     foreach ($spellcheck_langs as $key => $name) {
767       $editor_lang_set[] = ($key == $lang ? '+' : '') . JQ($name).'='.JQ($key);
768     }
769
770     $OUTPUT->include_script('googiespell.js');
771     $OUTPUT->add_script(sprintf(
772       "var googie = new GoogieSpell('\$__skin_path/images/googiespell/','?_task=utils&_action=spell&lang=', %s);\n".
773       "googie.lang_chck_spell = \"%s\";\n".
774       "googie.lang_rsm_edt = \"%s\";\n".
775       "googie.lang_close = \"%s\";\n".
776       "googie.lang_revert = \"%s\";\n".
777       "googie.lang_no_error_found = \"%s\";\n".
778       "googie.lang_learn_word = \"%s\";\n".
779       "googie.setLanguages(%s);\n".
780       "googie.setCurrentLanguage('%s');\n".
781       "googie.setSpellContainer('spellcheck-control');\n".
782       "googie.decorateTextarea('%s');\n".
783       "%s.set_env('spellcheck', googie);",
784       !empty($dictionary) ? 'true' : 'false',
785       JQ(Q(rcube_label('checkspelling'))),
786       JQ(Q(rcube_label('resumeediting'))),
787       JQ(Q(rcube_label('close'))),
788       JQ(Q(rcube_label('revertto'))),
789       JQ(Q(rcube_label('nospellerrors'))),
790       JQ(Q(rcube_label('addtodict'))),
791       json_serialize($spellcheck_langs),
792       $lang,
793       $attrib['id'],
794       JS_OBJECT_NAME), 'foot');
795
796     $OUTPUT->add_label('checking');
797     $OUTPUT->set_env('spellcheck_langs', join(',', $editor_lang_set));
798   }
799
800   $out .= "\n".'<iframe name="savetarget" src="program/blank.gif" style="width:0;height:0;border:none;visibility:hidden;"></iframe>';
801
802   return $out;
803 }
804
805
806 function rcmail_create_reply_body($body, $bodyIsHtml)
807 {
808   global $RCMAIL, $MESSAGE, $LINE_LENGTH;
809
810   // build reply prefix
811   $from = array_pop($RCMAIL->imap->decode_address_list($MESSAGE->get_header('from'), 1, false));
812   $prefix = rcube_label(array(
813     'name' => 'mailreplyintro',
814     'vars' => array(
815       'date' => format_date($MESSAGE->headers->date, $RCMAIL->config->get('date_long')),
816       'sender' => $from['name'] ? $from['name'] : rcube_idn_to_utf8($from['mailto']),
817     )
818   ));
819
820   if (!$bodyIsHtml) {
821     $body = preg_replace('/\r?\n/', "\n", $body);
822
823     // try to remove the signature
824     if ($RCMAIL->config->get('strip_existing_sig', true))
825       $body = rcmail_remove_signature($body);
826
827     // soft-wrap and quote message text
828     $body = rcmail_wrap_and_quote(rtrim($body, "\n"), $LINE_LENGTH);
829
830     $prefix .= "\n";
831     $suffix = '';
832
833     if ($RCMAIL->config->get('top_posting'))
834       $prefix = "\n\n\n" . $prefix;
835   }
836   else {
837     // save inline images to files
838     $cid_map = rcmail_write_inline_attachments($MESSAGE);
839     // set is_safe flag (we need this for html body washing)
840     rcmail_check_safe($MESSAGE);
841     // clean up html tags
842     $body = rcmail_wash_html($body, array('safe' => $MESSAGE->is_safe), $cid_map);
843
844     // build reply (quote content)
845     $prefix = '<p>' . Q($prefix) . "</p>\n";
846     $prefix .= '<blockquote>';
847
848     if ($RCMAIL->config->get('top_posting')) {
849       $prefix = '<br>' . $prefix;
850       $suffix = '</blockquote>';
851     }
852     else {
853       $suffix = '</blockquote><p></p>';
854     }
855   }
856
857   return $prefix.$body.$suffix;
858 }
859
860
861 function rcmail_create_forward_body($body, $bodyIsHtml)
862 {
863   global $RCMAIL, $MESSAGE, $COMPOSE;
864
865   // add attachments
866   if (!isset($COMPOSE['forward_attachments']) && is_array($MESSAGE->mime_parts))
867     $cid_map = rcmail_write_compose_attachments($MESSAGE, $bodyIsHtml);
868
869   $date    = format_date($MESSAGE->headers->date, $RCMAIL->config->get('date_long'));
870   $charset = $RCMAIL->output->get_charset();
871
872   if (!$bodyIsHtml)
873   {
874     $prefix = "\n\n\n-------- " . rcube_label('originalmessage') . " --------\n";
875     $prefix .= rcube_label('subject') . ': ' . $MESSAGE->subject . "\n";
876     $prefix .= rcube_label('date')    . ': ' . $date . "\n";
877     $prefix .= rcube_label('from')    . ': ' . $MESSAGE->get_header('from') . "\n";
878     $prefix .= rcube_label('to')      . ': ' . $MESSAGE->get_header('to') . "\n";
879
880     if ($MESSAGE->headers->cc)
881       $prefix .= rcube_label('cc') . ': ' . $MESSAGE->get_header('cc') . "\n";
882     if ($MESSAGE->headers->replyto && $MESSAGE->headers->replyto != $MESSAGE->headers->from)
883       $prefix .= rcube_label('replyto') . ': ' . $MESSAGE->get_header('replyto') . "\n";
884
885     $prefix .= "\n";
886   }
887   else
888   {
889     // set is_safe flag (we need this for html body washing)
890     rcmail_check_safe($MESSAGE);
891     // clean up html tags
892     $body = rcmail_wash_html($body, array('safe' => $MESSAGE->is_safe), $cid_map);
893
894     $prefix = sprintf(
895       "<br /><p>-------- " . rcube_label('originalmessage') . " --------</p>" .
896         "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\"><tbody>" .
897         "<tr><th align=\"right\" nowrap=\"nowrap\" valign=\"baseline\">%s: </th><td>%s</td></tr>" .
898         "<tr><th align=\"right\" nowrap=\"nowrap\" valign=\"baseline\">%s: </th><td>%s</td></tr>" .
899         "<tr><th align=\"right\" nowrap=\"nowrap\" valign=\"baseline\">%s: </th><td>%s</td></tr>" .
900         "<tr><th align=\"right\" nowrap=\"nowrap\" valign=\"baseline\">%s: </th><td>%s</td></tr>",
901       rcube_label('subject'), Q($MESSAGE->subject),
902       rcube_label('date'), Q($date),
903       rcube_label('from'), htmlspecialchars(Q($MESSAGE->get_header('from'), 'replace'), ENT_COMPAT, $charset),
904       rcube_label('to'), htmlspecialchars(Q($MESSAGE->get_header('to'), 'replace'), ENT_COMPAT, $charset));
905
906     if ($MESSAGE->headers->cc)
907       $prefix .= sprintf("<tr><th align=\"right\" nowrap=\"nowrap\" valign=\"baseline\">%s: </th><td>%s</td></tr>",
908         rcube_label('cc'),
909         htmlspecialchars(Q($MESSAGE->get_header('cc'), 'replace'), ENT_COMPAT, $charset));
910
911     if ($MESSAGE->headers->replyto && $MESSAGE->headers->replyto != $MESSAGE->headers->from)
912       $prefix .= sprintf("<tr><th align=\"right\" nowrap=\"nowrap\" valign=\"baseline\">%s: </th><td>%s</td></tr>",
913         rcube_label('replyto'),
914         htmlspecialchars(Q($MESSAGE->get_header('replyto'), 'replace'), ENT_COMPAT, $charset));
915
916     $prefix .= "</tbody></table><br>";
917   }
918
919   return $prefix.$body;
920 }
921
922
923 function rcmail_create_draft_body($body, $bodyIsHtml)
924 {
925   global $MESSAGE, $OUTPUT, $COMPOSE;
926
927   /**
928    * add attachments
929    * sizeof($MESSAGE->mime_parts can be 1 - e.g. attachment, but no text!
930    */
931   if (empty($COMPOSE['forward_attachments'])
932       && is_array($MESSAGE->mime_parts)
933       && count($MESSAGE->mime_parts) > 0)
934   {
935     $cid_map = rcmail_write_compose_attachments($MESSAGE, $bodyIsHtml);
936
937     // replace cid with href in inline images links
938     if ($cid_map)
939       $body = str_replace(array_keys($cid_map), array_values($cid_map), $body);
940   }
941
942   return $body;
943 }
944
945
946 function rcmail_remove_signature($body)
947 {
948   global $RCMAIL;
949
950   $len = strlen($body);
951   $sig_max_lines = $RCMAIL->config->get('sig_max_lines', 15);
952
953   while (($sp = strrpos($body, "-- \n", $sp ? -$len+$sp-1 : 0)) !== false) {
954     if ($sp == 0 || $body[$sp-1] == "\n") {
955       // do not touch blocks with more that X lines
956       if (substr_count($body, "\n", $sp) < $sig_max_lines) {
957         $body = substr($body, 0, max(0, $sp-1));
958       }
959       break;
960     }
961   }
962
963   return $body;
964 }
965
966
967 function rcmail_write_compose_attachments(&$message, $bodyIsHtml)
968 {
969   global $RCMAIL, $COMPOSE;
970
971   $cid_map = $messages = array();
972   foreach ((array)$message->mime_parts as $pid => $part)
973   {
974     if (($part->ctype_primary != 'message' || !$bodyIsHtml) && $part->ctype_primary != 'multipart' && 
975         ($part->disposition == 'attachment' || ($part->disposition == 'inline' && $bodyIsHtml) || $part->filename)
976         && $part->mimetype != 'application/ms-tnef'
977     ) {
978       $skip = false;
979       if ($part->mimetype == 'message/rfc822') {
980         $messages[] = $part->mime_id;
981       } else if ($messages) {
982         // skip attachments included in message/rfc822 attachment (#1486487)
983         foreach ($messages as $mimeid)
984           if (strpos($part->mime_id, $mimeid.'.') === 0) {
985             $skip = true;
986             break;
987           }
988       }
989
990       if (!$skip && ($attachment = rcmail_save_attachment($message, $pid))) {
991         $COMPOSE['attachments'][$attachment['id']] = $attachment;
992         if ($bodyIsHtml && ($part->content_id || $part->content_location)) {
993           $url = $RCMAIL->comm_path.'&_action=display-attachment&_file=rcmfile'.$attachment['id'].'&_id='.$COMPOSE['id'];
994           if ($part->content_id)
995             $cid_map['cid:'.$part->content_id] = $url;
996           else
997             $cid_map[$part->content_location] = $url;
998         }
999       }
1000     }
1001   }
1002
1003   $COMPOSE['forward_attachments'] = true;
1004
1005   return $cid_map;
1006 }
1007
1008
1009 function rcmail_write_inline_attachments(&$message)
1010 {
1011   global $RCMAIL, $COMPOSE;
1012
1013   $cid_map = array();
1014   foreach ((array)$message->mime_parts as $pid => $part) {
1015     if (($part->content_id || $part->content_location) && $part->filename) {
1016       if ($attachment = rcmail_save_attachment($message, $pid)) {
1017         $COMPOSE['attachments'][$attachment['id']] = $attachment;
1018         $url = $RCMAIL->comm_path.'&_action=display-attachment&_file=rcmfile'.$attachment['id'].'&_id='.$COMPOSE['id'];
1019         if ($part->content_id)
1020           $cid_map['cid:'.$part->content_id] = $url;
1021         else
1022           $cid_map[$part->content_location] = $url;
1023       }
1024     }
1025   }
1026
1027   return $cid_map;
1028 }
1029
1030 // Creates an attachment from the forwarded message
1031 function rcmail_write_forward_attachment(&$message)
1032 {
1033   global $RCMAIL, $COMPOSE;
1034
1035   if (strlen($message->subject)) {
1036     $name = mb_substr($message->subject, 0, 64) . '.eml';
1037   }
1038   else {
1039     $name = 'message_rfc822.eml';
1040   }
1041
1042   $mem_limit = parse_bytes(ini_get('memory_limit'));
1043   $curr_mem = function_exists('memory_get_usage') ? memory_get_usage() : 16*1024*1024; // safe value: 16MB
1044   $data = $path = null;
1045
1046   // don't load too big attachments into memory
1047   if ($mem_limit > 0 && $message->size > $mem_limit - $curr_mem) {
1048     $temp_dir = unslashify($RCMAIL->config->get('temp_dir'));
1049     $path = tempnam($temp_dir, 'rcmAttmnt');
1050     if ($fp = fopen($path, 'w')) {
1051       $RCMAIL->imap->get_raw_body($message->uid, $fp);
1052       fclose($fp);
1053     } else
1054       return false;
1055   } else {
1056     $data = $RCMAIL->imap->get_raw_body($message->uid);
1057   }
1058
1059   $attachment = array(
1060     'group' => $COMPOSE['id'],
1061     'name' => $name,
1062     'mimetype' => 'message/rfc822',
1063     'data' => $data,
1064     'path' => $path,
1065     'size' => $path ? filesize($path) : strlen($data),
1066   );
1067
1068   $attachment = $RCMAIL->plugins->exec_hook('attachment_save', $attachment);
1069
1070   if ($attachment['status']) {
1071     unset($attachment['data'], $attachment['status'], $attachment['content_id'], $attachment['abort']);
1072     $COMPOSE['attachments'][$attachment['id']] = $attachment;
1073     return true;
1074   } else if ($path) {
1075     @unlink($path);
1076   }
1077
1078   return false;
1079 }
1080
1081
1082 function rcmail_save_attachment(&$message, $pid)
1083 {
1084   global $COMPOSE;
1085
1086   $rcmail = rcmail::get_instance();
1087   $part = $message->mime_parts[$pid];
1088   $mem_limit = parse_bytes(ini_get('memory_limit'));
1089   $curr_mem = function_exists('memory_get_usage') ? memory_get_usage() : 16*1024*1024; // safe value: 16MB
1090   $data = $path = null;
1091
1092   // don't load too big attachments into memory
1093   if ($mem_limit > 0 && $part->size > $mem_limit - $curr_mem) {
1094     $temp_dir = unslashify($rcmail->config->get('temp_dir'));
1095     $path = tempnam($temp_dir, 'rcmAttmnt');
1096     if ($fp = fopen($path, 'w')) {
1097       $message->get_part_content($pid, $fp);
1098       fclose($fp);
1099     } else
1100       return false;
1101   } else {
1102     $data = $message->get_part_content($pid);
1103   }
1104
1105   $attachment = array(
1106     'group' => $COMPOSE['id'],
1107     'name' => $part->filename ? $part->filename : 'Part_'.$pid.'.'.$part->ctype_secondary,
1108     'mimetype' => $part->ctype_primary . '/' . $part->ctype_secondary,
1109     'content_id' => $part->content_id,
1110     'data' => $data,
1111     'path' => $path,
1112     'size' => $path ? filesize($path) : strlen($data),
1113   );
1114
1115   $attachment = $rcmail->plugins->exec_hook('attachment_save', $attachment);
1116
1117   if ($attachment['status']) {
1118     unset($attachment['data'], $attachment['status'], $attachment['content_id'], $attachment['abort']);
1119     return $attachment;
1120   } else if ($path) {
1121     @unlink($path);
1122   }
1123
1124   return false;
1125 }
1126
1127 function rcmail_save_image($path, $mimetype='')
1128 {
1129   global $COMPOSE;
1130
1131   // handle attachments in memory
1132   $data = file_get_contents($path);
1133
1134   $attachment = array(
1135     'group' => $COMPOSE['id'],
1136     'name' => rcmail_basename($path),
1137     'mimetype' => $mimetype ? $mimetype : rc_mime_content_type($path, $name),
1138     'data' => $data,
1139     'size' => strlen($data),
1140   );
1141
1142   $attachment = rcmail::get_instance()->plugins->exec_hook('attachment_save', $attachment);
1143
1144   if ($attachment['status']) {
1145     unset($attachment['data'], $attachment['status'], $attachment['content_id'], $attachment['abort']);
1146     return $attachment;
1147   }
1148
1149   return false;
1150 }
1151
1152 function rcmail_basename($filename)
1153 {
1154   // basename() is not unicode safe and locale dependent
1155   if (stristr(PHP_OS, 'win') || stristr(PHP_OS, 'netware')) {
1156     return preg_replace('/^.*[\\\\\\/]/', '', $filename);
1157   } else {
1158     return preg_replace('/^.*[\/]/', '', $filename);
1159   }
1160 }
1161
1162 function rcmail_compose_subject($attrib)
1163 {
1164   global $MESSAGE, $COMPOSE, $compose_mode;
1165
1166   list($form_start, $form_end) = get_form_tags($attrib);
1167   unset($attrib['form']);
1168
1169   $attrib['name'] = '_subject';
1170   $attrib['spellcheck'] = 'true';
1171   $textfield = new html_inputfield($attrib);
1172
1173   $subject = '';
1174
1175   // use subject from post
1176   if (isset($_POST['_subject'])) {
1177     $subject = get_input_value('_subject', RCUBE_INPUT_POST, TRUE);
1178   }
1179   // create a reply-subject
1180   else if ($compose_mode == RCUBE_COMPOSE_REPLY) {
1181     if (preg_match('/^re:/i', $MESSAGE->subject))
1182       $subject = $MESSAGE->subject;
1183     else
1184       $subject = 'Re: '.$MESSAGE->subject;
1185   }
1186   // create a forward-subject
1187   else if ($compose_mode == RCUBE_COMPOSE_FORWARD) {
1188     if (preg_match('/^fwd:/i', $MESSAGE->subject))
1189       $subject = $MESSAGE->subject;
1190     else
1191       $subject = 'Fwd: '.$MESSAGE->subject;
1192   }
1193   // creeate a draft-subject
1194   else if ($compose_mode == RCUBE_COMPOSE_DRAFT || $compose_mode == RCUBE_COMPOSE_EDIT) {
1195     $subject = $MESSAGE->subject;
1196   }
1197   else if (!empty($COMPOSE['param']['subject'])) {
1198     $subject = $COMPOSE['param']['subject'];
1199   }
1200
1201   $out = $form_start ? "$form_start\n" : '';
1202   $out .= $textfield->show($subject);
1203   $out .= $form_end ? "\n$form_end" : '';
1204
1205   return $out;
1206 }
1207
1208
1209 function rcmail_compose_attachment_list($attrib)
1210 {
1211   global $OUTPUT, $CONFIG, $COMPOSE;
1212
1213   // add ID if not given
1214   if (!$attrib['id'])
1215     $attrib['id'] = 'rcmAttachmentList';
1216
1217   $out = "\n";
1218   $jslist = array();
1219
1220   if (is_array($COMPOSE['attachments'])) {
1221     if ($attrib['deleteicon']) {
1222       $button = html::img(array(
1223         'src' => $CONFIG['skin_path'] . $attrib['deleteicon'],
1224         'alt' => rcube_label('delete')
1225       ));
1226     }
1227     else
1228       $button = Q(rcube_label('delete'));
1229
1230     foreach ($COMPOSE['attachments'] as $id => $a_prop)
1231     {
1232       if (empty($a_prop))
1233         continue;
1234
1235       $out .= html::tag('li', array('id' => 'rcmfile'.$id),
1236         html::a(array(
1237             'href' => "#delete",
1238             'title' => rcube_label('delete'),
1239             'onclick' => sprintf("return %s.command('remove-attachment','rcmfile%s', this)", JS_OBJECT_NAME, $id)),
1240           $button) . Q($a_prop['name']));
1241         
1242         $jslist['rcmfile'.$id] = array('name' => $a_prop['name'], 'complete' => true, 'mimetype' => $a_prop['mimetype']);
1243     }
1244   }
1245
1246   if ($attrib['deleteicon'])
1247     $COMPOSE['deleteicon'] = $CONFIG['skin_path'] . $attrib['deleteicon'];
1248   if ($attrib['cancelicon'])
1249     $OUTPUT->set_env('cancelicon', $CONFIG['skin_path'] . $attrib['cancelicon']);
1250   if ($attrib['loadingicon'])
1251     $OUTPUT->set_env('loadingicon', $CONFIG['skin_path'] . $attrib['loadingicon']);
1252
1253   $OUTPUT->set_env('attachments', $jslist);
1254   $OUTPUT->add_gui_object('attachmentlist', $attrib['id']);
1255     
1256   return html::tag('ul', $attrib, $out, html::$common_attrib);
1257 }
1258
1259
1260 function rcmail_compose_attachment_form($attrib)
1261 {
1262   global $RCMAIL, $OUTPUT;
1263
1264   // add ID if not given
1265   if (!$attrib['id'])
1266     $attrib['id'] = 'rcmUploadbox';
1267
1268   // Get filesize, enable upload progress bar
1269   $max_filesize = rcube_upload_init();
1270
1271   $button = new html_inputfield(array('type' => 'button'));
1272
1273   $out = html::div($attrib,
1274     $OUTPUT->form_tag(array('name' => 'uploadform', 'method' => 'post', 'enctype' => 'multipart/form-data'),
1275       html::div(null, rcmail_compose_attachment_field(array('size' => $attrib['attachmentfieldsize']))) .
1276       html::div('hint', rcube_label(array('name' => 'maxuploadsize', 'vars' => array('size' => $max_filesize)))) .
1277       html::div('buttons',
1278         $button->show(rcube_label('close'), array('class' => 'button', 'onclick' => "$('#$attrib[id]').hide()")) . ' ' .
1279         $button->show(rcube_label('upload'), array('class' => 'button mainaction', 'onclick' => JS_OBJECT_NAME . ".command('send-attachment', this.form)"))
1280       )
1281     )
1282   );
1283
1284   $OUTPUT->add_gui_object('uploadbox', $attrib['id']);
1285   return $out;
1286 }
1287
1288
1289 function rcmail_compose_attachment_field($attrib)
1290 {
1291   $attrib['type'] = 'file';
1292   $attrib['name'] = '_attachments[]';
1293   $attrib['multiple'] = 'multiple';
1294
1295   $field = new html_inputfield($attrib);
1296   return $field->show();
1297 }
1298
1299
1300 function rcmail_priority_selector($attrib)
1301 {
1302   global $MESSAGE;
1303   
1304   list($form_start, $form_end) = get_form_tags($attrib);
1305   unset($attrib['form']);
1306
1307   $attrib['name'] = '_priority';
1308   $selector = new html_select($attrib);
1309
1310   $selector->add(array(rcube_label('lowest'),
1311                        rcube_label('low'),
1312                        rcube_label('normal'),
1313                        rcube_label('high'),
1314                        rcube_label('highest')),
1315                  array(5, 4, 0, 2, 1));
1316
1317   if (isset($_POST['_priority']))
1318     $sel = $_POST['_priority'];
1319   else if (intval($MESSAGE->headers->priority) != 3)
1320     $sel = intval($MESSAGE->headers->priority);
1321   else
1322     $sel = 0;
1323
1324   $out = $form_start ? "$form_start\n" : '';
1325   $out .= $selector->show($sel);
1326   $out .= $form_end ? "\n$form_end" : '';
1327
1328   return $out;
1329 }
1330
1331
1332 function rcmail_receipt_checkbox($attrib)
1333 {
1334   global $RCMAIL, $MESSAGE, $compose_mode;
1335
1336   list($form_start, $form_end) = get_form_tags($attrib);
1337   unset($attrib['form']);
1338
1339   if (!isset($attrib['id']))
1340     $attrib['id'] = 'receipt';  
1341
1342   $attrib['name'] = '_receipt';
1343   $attrib['value'] = '1';
1344   $checkbox = new html_checkbox($attrib);
1345
1346   if ($MESSAGE && in_array($compose_mode, array(RCUBE_COMPOSE_DRAFT, RCUBE_COMPOSE_EDIT)))
1347     $mdn_default = (bool) $MESSAGE->headers->mdn_to;
1348   else
1349     $mdn_default = $RCMAIL->config->get('mdn_default');
1350
1351   $out = $form_start ? "$form_start\n" : '';
1352   $out .= $checkbox->show($mdn_default);
1353   $out .= $form_end ? "\n$form_end" : '';
1354
1355   return $out;
1356 }
1357
1358
1359 function rcmail_dsn_checkbox($attrib)
1360 {
1361   global $RCMAIL;
1362
1363   list($form_start, $form_end) = get_form_tags($attrib);
1364   unset($attrib['form']);
1365
1366   if (!isset($attrib['id']))
1367     $attrib['id'] = 'dsn';
1368
1369   $attrib['name'] = '_dsn';
1370   $attrib['value'] = '1';
1371   $checkbox = new html_checkbox($attrib);
1372
1373   $out = $form_start ? "$form_start\n" : '';
1374   $out .= $checkbox->show($RCMAIL->config->get('dsn_default'));
1375   $out .= $form_end ? "\n$form_end" : '';
1376
1377   return $out;
1378 }
1379
1380
1381 function rcmail_editor_selector($attrib)
1382 {
1383   global $CONFIG, $MESSAGE, $compose_mode;
1384
1385   // determine whether HTML or plain text should be checked
1386   $useHtml = rcmail_compose_editor_mode();
1387
1388   if (empty($attrib['editorid']))
1389     $attrib['editorid'] = 'rcmComposeBody';
1390
1391   if (empty($attrib['name']))
1392     $attrib['name'] = 'editorSelect';
1393
1394   $attrib['onchange'] = "return rcmail_toggle_editor(this, '".$attrib['editorid']."', '_is_html')";
1395
1396   $select = new html_select($attrib);
1397
1398   $select->add(Q(rcube_label('htmltoggle')), 'html');
1399   $select->add(Q(rcube_label('plaintoggle')), 'plain');
1400
1401   return $select->show($useHtml ? 'html' : 'plain');
1402
1403   foreach ($choices as $value => $text) {
1404     $attrib['id'] = '_' . $value;
1405     $attrib['value'] = $value;
1406     $selector .= $radio->show($chosenvalue, $attrib) . html::label($attrib['id'], Q(rcube_label($text)));
1407   }
1408
1409   return $selector;
1410 }
1411
1412
1413 function rcmail_store_target_selection($attrib)
1414 {
1415   global $COMPOSE;
1416
1417   $attrib['name'] = '_store_target';
1418   $select = rcmail_mailbox_select(array_merge($attrib, array(
1419     'noselection' => '- '.rcube_label('dontsave').' -',
1420     'folder_filter' => 'mail',
1421     'folder_rights' => 'w',
1422   )));
1423   return $select->show($COMPOSE['param']['sent_mbox'], $attrib);
1424 }
1425
1426
1427 function rcmail_check_sent_folder($folder, $create=false)
1428 {
1429   global $IMAP;
1430
1431   if ($IMAP->mailbox_exists($folder, true)) {
1432     return true;
1433   }
1434
1435   // folder may exist but isn't subscribed (#1485241)
1436   if ($create) {
1437     if (!$IMAP->mailbox_exists($folder))
1438       return $IMAP->create_mailbox($folder, true);
1439     else
1440       return $IMAP->subscribe($folder);
1441   }
1442
1443   return false;
1444 }
1445
1446
1447 function get_form_tags($attrib)
1448 {
1449   global $RCMAIL, $MESSAGE_FORM, $COMPOSE;
1450
1451   $form_start = '';
1452   if (!$MESSAGE_FORM)
1453   {
1454     $hiddenfields = new html_hiddenfield(array('name' => '_task', 'value' => $RCMAIL->task));
1455     $hiddenfields->add(array('name' => '_action', 'value' => 'send'));
1456     $hiddenfields->add(array('name' => '_id', 'value' => $COMPOSE['id']));
1457
1458     $form_start = empty($attrib['form']) ? $RCMAIL->output->form_tag(array('name' => "form", 'method' => "post")) : '';
1459     $form_start .= $hiddenfields->show();
1460   }
1461
1462   $form_end = ($MESSAGE_FORM && !strlen($attrib['form'])) ? '</form>' : '';
1463   $form_name = !empty($attrib['form']) ? $attrib['form'] : 'form';
1464
1465   if (!$MESSAGE_FORM)
1466     $RCMAIL->output->add_gui_object('messageform', $form_name);
1467
1468   $MESSAGE_FORM = $form_name;
1469
1470   return array($form_start, $form_end);
1471 }
1472
1473
1474 // register UI objects
1475 $OUTPUT->add_handlers(array(
1476   'composeheaders' => 'rcmail_compose_headers',
1477   'composesubject' => 'rcmail_compose_subject',
1478   'composebody' => 'rcmail_compose_body',
1479   'composeattachmentlist' => 'rcmail_compose_attachment_list',
1480   'composeattachmentform' => 'rcmail_compose_attachment_form',
1481   'composeattachment' => 'rcmail_compose_attachment_field',
1482   'priorityselector' => 'rcmail_priority_selector',
1483   'editorselector' => 'rcmail_editor_selector',
1484   'receiptcheckbox' => 'rcmail_receipt_checkbox',
1485   'dsncheckbox' => 'rcmail_dsn_checkbox',
1486   'storetarget' => 'rcmail_store_target_selection',
1487 ));
1488
1489 $OUTPUT->send('compose');
1490
1491