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