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