]> git.donarmstrong.com Git - roundcube.git/blob - program/steps/mail/compose.inc
Imported Upstream version 0.3
[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 2909 2009-09-03 06:49:00Z 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 if (!is_array($_SESSION['compose']) || $_SESSION['compose']['id'] != get_input_value('_id', RCUBE_INPUT_GET))
37 {
38   rcmail_compose_cleanup();
39   $_SESSION['compose'] = array(
40     'id' => uniqid(rand()),
41     'param' => request2param(RCUBE_INPUT_GET),
42     'mailbox' => $IMAP->get_mailbox_name(),
43   );
44   
45   // process values like "mailto:foo@bar.com?subject=new+message&cc=another"
46   if ($_SESSION['compose']['param']['to']) {
47     $mailto = explode('?', $_SESSION['compose']['param']['to']);
48     if (count($mailto) > 1) {
49       $_SESSION['compose']['param']['to'] = $mailto[0];
50       parse_str($mailto[1], $query);
51       foreach ($query as $f => $val)
52         $_SESSION['compose']['param'][$f] = $val;
53     }
54   }
55   
56   // pipe compose parameters thru plugins
57   $plugin = $RCMAIL->plugins->exec_hook('message_compose', $_SESSION['compose']);
58   $_SESSION['compose']['param'] = $plugin['param'];
59   
60   // add attachments listed by message_compose hook
61   if (is_array($plugin['attachments'])) {
62     foreach ($plugin['attachments'] as $attach) {
63       // we have structured data
64       if (is_array($attach)) {
65         $attachment = $attach;
66       }
67       // only a file path is given
68       else {
69         $filename = basename($attach);
70         $attachment = array(
71           'name' => $filename,
72           'mimetype' => rc_mime_content_type($attach, $filename),
73           'path' => $attach
74         );
75       }
76       
77       // save attachment if valid
78       if (($attachment['data'] && $attachment['name']) || ($attachment['path'] && file_exists($attachment['path']))) {
79         $attachment = rcmail::get_instance()->plugins->exec_hook('save_attachment', $attachment);
80       }
81       
82       if ($attachment['status'] && !$attachment['abort']) {
83         unset($attachment['data'], $attachment['status'], $attachment['abort']);
84         $_SESSION['compose']['attachments'][$attachment['id']] = $attachment;
85       }
86     }
87   }
88
89   // redirect to a unique URL with all parameters stored in session
90   $OUTPUT->redirect(array('_action' => 'compose', '_id' => $_SESSION['compose']['id']));
91 }
92
93
94 // add some labels to client
95 $OUTPUT->add_label('nosubject', 'nosenderwarning', 'norecipientwarning', 'nosubjectwarning',
96     'nobodywarning', 'notsentwarning', 'savingmessage', 'sendingmessage', 'messagesaved',
97     'converting', 'editorwarning', 'searching');
98
99 // add config parameters to client script
100 if (!empty($CONFIG['drafts_mbox'])) {
101   $OUTPUT->set_env('drafts_mailbox', $CONFIG['drafts_mbox']);
102   $OUTPUT->set_env('draft_autosave', $CONFIG['draft_autosave']);
103 }
104 // set current mailbox in client environment
105 $OUTPUT->set_env('mailbox', $IMAP->get_mailbox_name());
106
107 // get reference message and set compose mode
108 if ($msg_uid = $_SESSION['compose']['param']['reply_uid'])
109   $compose_mode = RCUBE_COMPOSE_REPLY;
110 else if ($msg_uid = $_SESSION['compose']['param']['forward_uid'])
111   $compose_mode = RCUBE_COMPOSE_FORWARD;
112 else if ($msg_uid = $_SESSION['compose']['param']['uid'])
113   $compose_mode = RCUBE_COMPOSE_EDIT;
114 else if ($msg_uid = $_SESSION['compose']['param']['draft_uid']) {
115   $RCMAIL->imap->set_mailbox($CONFIG['drafts_mbox']);
116   $compose_mode = RCUBE_COMPOSE_DRAFT;
117 }
118
119 if (!empty($msg_uid))
120 {
121   // similar as in program/steps/mail/show.inc
122   // re-set 'prefer_html' to have possibility to use html part for compose
123   $CONFIG['prefer_html'] = $CONFIG['htmleditor'] || $compose_mode == RCUBE_COMPOSE_DRAFT || $compose_mode == RCUBE_COMPOSE_EDIT;
124   $MESSAGE = new rcube_message($msg_uid);
125   
126   if (!empty($MESSAGE->headers->charset))
127     $IMAP->set_charset($MESSAGE->headers->charset);
128     
129   if ($compose_mode == RCUBE_COMPOSE_REPLY)
130   {
131     $_SESSION['compose']['reply_uid'] = $msg_uid;
132     $_SESSION['compose']['reply_msgid'] = $MESSAGE->headers->messageID;
133     $_SESSION['compose']['references']  = trim($MESSAGE->headers->references . " " . $MESSAGE->headers->messageID);
134
135     if (!empty($_SESSION['compose']['param']['all']))
136       $MESSAGE->reply_all = 1;
137   }
138   else if ($compose_mode == RCUBE_COMPOSE_DRAFT)
139   {
140     if($MESSAGE->headers->in_reply_to)
141     {
142       // TODO: how to get reply_uid/forward_uid value, maybe we must set X-Reply-UID/X-Forward-UID
143       // $_SESSION['compose']['reply_uid'] = ?
144       // $_SESSION['compose']['forward_uid'] = ?
145       $_SESSION['compose']['reply_msgid'] = '<'.$MESSAGE->headers->in_reply_to.'>';
146     }
147     $_SESSION['compose']['references']  = $MESSAGE->headers->references;
148   }
149   else if ($compose_mode == RCUBE_COMPOSE_FORWARD)
150   {
151     $_SESSION['compose']['forward_uid'] = $msg_uid;
152   }
153 }
154
155 /****** compose mode functions ********/
156
157
158 function rcmail_compose_headers($attrib)
159 {
160   global $IMAP, $MESSAGE, $DB, $compose_mode;
161   static $sa_recipients = array();
162
163   list($form_start, $form_end) = get_form_tags($attrib);
164   
165   $out = '';
166   $part = strtolower($attrib['part']);
167   
168   switch ($part)
169   {
170     case 'from':
171       return rcmail_compose_header_from($attrib);
172
173     case 'to':
174       $fname = '_to';
175       $header = $param = 'to';
176       
177       // we have a set of recipients stored is session
178       if (($mailto_id = $_SESSION['compose']['param']['mailto']) && $_SESSION['mailto'][$mailto_id])
179         $fvalue = urldecode($_SESSION['mailto'][$mailto_id]);
180       
181     case 'cc':
182       if (!$fname)
183       {
184         $fname = '_cc';
185         $header = $param = 'cc';
186       }
187     case 'bcc':
188       if (!$fname)
189       {
190         $fname = '_bcc';
191         $header = $param = 'bcc';
192       }
193         
194       $allow_attrib = array('id', 'class', 'style', 'cols', 'rows', 'tabindex');
195       $field_type = 'html_textarea';
196       break;
197
198     case 'replyto':
199     case 'reply-to':
200       $fname = '_replyto';
201       $param = 'replyto';
202       $allow_attrib = array('id', 'class', 'style', 'size', 'tabindex');
203       $field_type = 'html_inputfield';
204       break;
205   }
206  
207   if ($fname && !empty($_POST[$fname])) {
208     $fvalue = get_input_value($fname, RCUBE_INPUT_POST, TRUE);
209   }
210   else if ($fname && !$fvalue && !empty($_SESSION['compose']['param'][$param])) {
211     $fvalue = $_SESSION['compose']['param'][$param];
212   }
213   else if ($header && $compose_mode == RCUBE_COMPOSE_REPLY) {
214     // get recipent address(es) out of the message headers
215     if ($header=='to' && !empty($MESSAGE->headers->replyto))
216       $fvalue = $MESSAGE->headers->replyto;
217
218     else if ($header=='to' && !empty($MESSAGE->headers->from))
219       $fvalue = $MESSAGE->headers->from;
220
221     // add recipent of original message if reply to all
222     else if ($header=='cc' && !empty($MESSAGE->reply_all))
223     {
224       if ($v = $MESSAGE->headers->to)
225         $fvalue .= $v;
226
227       if ($v = $MESSAGE->headers->cc)
228         $fvalue .= (!empty($fvalue) ? ', ' : '') . $v;
229     }
230
231     // split recipients and put them back together in a unique way
232     if (!empty($fvalue))
233     {
234       $to_addresses = $IMAP->decode_address_list($fvalue);
235       $fvalue = '';
236
237       foreach ($to_addresses as $addr_part)
238       {
239         if (!empty($addr_part['mailto'])
240             && !in_array($addr_part['mailto'], $sa_recipients)
241             && (!$MESSAGE->compose_from
242                 || !in_array_nocase($addr_part['mailto'], $MESSAGE->compose_from)
243                 || (count($to_addresses)==1 && $header=='to'))) // allow reply to yourself
244         {
245           $fvalue .= (strlen($fvalue) ? ', ':'').$addr_part['string'];
246           $sa_recipients[] = $addr_part['mailto'];
247         }
248       }
249     }
250   }
251   else if ($header && in_array($compose_mode, array(RCUBE_COMPOSE_DRAFT, RCUBE_COMPOSE_EDIT)))
252   {
253     // get drafted headers
254     if ($header=='to' && !empty($MESSAGE->headers->to))
255       $fvalue = $MESSAGE->get_header('to');
256
257     if ($header=='cc' && !empty($MESSAGE->headers->cc))
258       $fvalue = $MESSAGE->get_header('cc');
259
260     if ($header=='bcc' && !empty($MESSAGE->headers->bcc))
261       $fvalue = $MESSAGE->get_header('bcc');
262   }
263
264         
265   if ($fname && $field_type)
266   {
267     // pass the following attributes to the form class
268     $field_attrib = array('name' => $fname, 'spellcheck' => 'false');
269     foreach ($attrib as $attr => $value)
270       if (in_array($attr, $allow_attrib))
271         $field_attrib[$attr] = $value;
272
273     // create teaxtarea object
274     $input = new $field_type($field_attrib);
275     $out = $input->show($fvalue);
276   }
277   
278   if ($form_start)
279     $out = $form_start.$out;
280
281   return $out;  
282 }
283
284
285
286 function rcmail_compose_header_from($attrib)
287 {
288   global $IMAP, $MESSAGE, $DB, $USER, $OUTPUT, $compose_mode;
289     
290   // pass the following attributes to the form class
291   $field_attrib = array('name' => '_from');
292   foreach ($attrib as $attr => $value)
293     if (in_array($attr, array('id', 'class', 'style', 'size', 'tabindex')))
294       $field_attrib[$attr] = $value;
295
296   // extract all recipients of the reply-message
297   $a_recipients = array();
298   if ($compose_mode == RCUBE_COMPOSE_REPLY && is_object($MESSAGE->headers))
299   {
300     $MESSAGE->compose_from = array();
301
302     $a_to = $IMAP->decode_address_list($MESSAGE->headers->to);
303     foreach ($a_to as $addr)
304     {
305       if (!empty($addr['mailto']))
306         $a_recipients[] = mb_strtolower($addr['mailto']);
307     }
308
309     if (!empty($MESSAGE->headers->cc))
310     {
311       $a_cc = $IMAP->decode_address_list($MESSAGE->headers->cc);
312       foreach ($a_cc as $addr)
313       {
314         if (!empty($addr['mailto']))
315           $a_recipients[] = mb_strtolower($addr['mailto']);
316       }
317     }
318   }
319
320   // get this user's identities
321   $user_identities = $USER->list_identities();
322
323   if (count($user_identities))
324   {
325     $from_id = 0;
326     $a_signatures = array();
327
328     $field_attrib['onchange'] = JS_OBJECT_NAME.".change_identity(this)";
329     $select_from = new html_select($field_attrib);
330
331     foreach ($user_identities as $sql_arr)
332     {
333       $identity_id = $sql_arr['identity_id'];
334       $select_from->add(format_email_recipient($sql_arr['email'], $sql_arr['name']), $identity_id);
335
336       // add signature to array
337       if (!empty($sql_arr['signature']) && empty($_SESSION['compose']['param']['nosig']))
338       {
339         $a_signatures[$identity_id]['text'] = $sql_arr['signature'];
340         $a_signatures[$identity_id]['is_html'] = ($sql_arr['html_signature'] == 1) ? true : false;
341         if ($a_signatures[$identity_id]['is_html'])
342         {
343             $h2t = new html2text($a_signatures[$identity_id]['text'], false, false);
344             $a_signatures[$identity_id]['plain_text'] = trim($h2t->get_text());
345         }
346       }
347
348       if ($compose_mode == RCUBE_COMPOSE_REPLY && is_array($MESSAGE->compose_from))
349         $MESSAGE->compose_from[] = $sql_arr['email'];
350
351       if (empty($_POST['_from']))
352       {
353         // set draft's identity
354         if ($compose_mode == RCUBE_COMPOSE_DRAFT && strstr($MESSAGE->headers->from, $sql_arr['email']))
355           $from_id = $sql_arr['identity_id'];
356         // set identity if it's one of the reply-message recipients (with prio for default identity)
357         else if (in_array(mb_strtolower($sql_arr['email']), $a_recipients) && (empty($from_id) || $sql_arr['standard']))
358           $from_id = $sql_arr['identity_id'];
359       }
360     }
361
362     // overwrite identity selection with post parameter
363     if (!empty($_POST['_from']))
364       $from_id = get_input_value('_from', RCUBE_INPUT_POST);
365
366     $out = $select_from->show($from_id);
367
368     // add signatures to client
369     $OUTPUT->set_env('signatures', $a_signatures);
370   }
371   else
372   {
373     $input_from = new html_inputfield($field_attrib);
374     $out = $input_from->show($_POST['_from']);
375   }
376   
377   if ($form_start)
378     $out = $form_start.$out;
379
380   return $out;
381 }
382
383
384 function rcmail_compose_body($attrib)
385 {
386   global $RCMAIL, $CONFIG, $OUTPUT, $MESSAGE, $compose_mode;
387   
388   list($form_start, $form_end) = get_form_tags($attrib);
389   unset($attrib['form']);
390   
391   if (empty($attrib['id']))
392     $attrib['id'] = 'rcmComposeBody';
393
394   $attrib['name'] = '_message';
395
396   if ($CONFIG['htmleditor'] || (($compose_mode == RCUBE_COMPOSE_DRAFT || $compose_mode == RCUBE_COMPOSE_EDIT) && $MESSAGE->has_html_part()))
397     $isHtml = true;
398   else
399     $isHtml = false;
400
401   $body = '';
402
403   // use posted message body
404   if (!empty($_POST['_message']))
405   {
406     $body = get_input_value('_message', RCUBE_INPUT_POST, true);
407   }
408   else if ($_SESSION['compose']['param']['body'])
409   {
410     $body = $_SESSION['compose']['param']['body'];
411     $isHtml = false;
412   }
413   else if ($compose_mode)
414   {
415     if (($isHtml || $compose_mode == RCUBE_COMPOSE_DRAFT) && $MESSAGE->has_html_part())
416     {
417       $body = $MESSAGE->first_html_part();
418       $isHtml = true;
419     }
420     else
421     {
422       $body = $MESSAGE->first_text_part();
423       $isHtml = false;
424     }
425
426     // compose reply-body
427     if ($compose_mode == RCUBE_COMPOSE_REPLY)
428       $body = rcmail_create_reply_body($body, $isHtml);
429     // forward message body inline
430     else if ($compose_mode == RCUBE_COMPOSE_FORWARD)
431       $body = rcmail_create_forward_body($body, $isHtml);
432     // load draft message body
433     else if ($compose_mode == RCUBE_COMPOSE_DRAFT || $compose_mode == RCUBE_COMPOSE_EDIT)
434       $body = rcmail_create_draft_body($body, $isHtml);
435   }
436   else if (!empty($_SESSION['compose']['param']['body']))
437   {
438     $body = $_SESSION['compose']['param']['body'];
439   }
440
441   $out = $form_start ? "$form_start\n" : '';
442
443   $saveid = new html_hiddenfield(array('name' => '_draft_saveid', 'value' => $compose_mode==RCUBE_COMPOSE_DRAFT ? str_replace(array('<','>'), "", $MESSAGE->headers->messageID) : ''));
444   $out .= $saveid->show();
445
446   $drafttoggle = new html_hiddenfield(array('name' => '_draft', 'value' => 'yes'));
447   $out .= $drafttoggle->show();
448
449   $msgtype = new html_hiddenfield(array('name' => '_is_html', 'value' => ($isHtml?"1":"0")));
450   $out .= $msgtype->show();
451
452   // If desired, set this textarea to be editable by TinyMCE
453   if ($isHtml) $attrib['class'] = 'mce_editor';
454   $textarea = new html_textarea($attrib);
455   $out .= $textarea->show($body);
456   $out .= $form_end ? "\n$form_end" : '';
457
458   $OUTPUT->set_env('composebody', $attrib['id']);
459
460   // include HTML editor
461   rcube_html_editor();
462   
463   // include GoogieSpell
464   if (!empty($CONFIG['enable_spellcheck'])) {
465
466     $lang = strtolower(substr($_SESSION['language'], 0, 2));
467   
468     $spellcheck_langs = (array)$RCMAIL->config->get('spellcheck_languages', array('da'=>'Dansk', 'de'=>'Deutsch', 'en' => 'English', 'es'=>'Español', 'fr'=>'Français', 'it'=>'Italiano', 'nl'=>'Nederlands', 'pl'=>'Polski', 'pt'=>'Português', 'fi'=>'Suomi', 'sv'=>'Svenska'));
469     if (!$spellcheck_langs[$lang])
470       $lang = 'en';
471     
472     $editor_lang_set = array();
473     foreach ($spellcheck_langs as $key => $name) {
474       $editor_lang_set[] = ($key == $lang ? '+' : '') . JQ($name).'='.JQ($key);
475       }
476     
477     $OUTPUT->include_script('googiespell.js');
478     $OUTPUT->add_script(sprintf(
479       "var googie = new GoogieSpell('\$__skin_path/images/googiespell/','%s&_action=spell&lang=');\n".
480       "googie.lang_chck_spell = \"%s\";\n".
481       "googie.lang_rsm_edt = \"%s\";\n".
482       "googie.lang_close = \"%s\";\n".
483       "googie.lang_revert = \"%s\";\n".
484       "googie.lang_no_error_found = \"%s\";\n".
485       "googie.setLanguages(%s);\n".
486       "googie.setCurrentLanguage('%s');\n".
487       "googie.setSpellContainer('spellcheck-control');\n".
488       "googie.decorateTextarea('%s');\n".
489       "%s.set_env('spellcheck', googie);",
490       $RCMAIL->comm_path,
491       JQ(Q(rcube_label('checkspelling'))),
492       JQ(Q(rcube_label('resumeediting'))),
493       JQ(Q(rcube_label('close'))),
494       JQ(Q(rcube_label('revertto'))),
495       JQ(Q(rcube_label('nospellerrors'))),
496       json_serialize($spellcheck_langs),
497       $lang,
498       $attrib['id'],
499       JS_OBJECT_NAME), 'foot');
500
501     $OUTPUT->add_label('checking');
502     $OUTPUT->set_env('spellcheck_langs', join(',', $editor_lang_set));
503   }
504  
505   $out .= "\n".'<iframe name="savetarget" src="program/blank.gif" style="width:0;height:0;border:none;visibility:hidden;"></iframe>';
506
507   return $out;
508 }
509
510
511 function rcmail_create_reply_body($body, $bodyIsHtml)
512 {
513   global $IMAP, $MESSAGE, $OUTPUT;
514
515   if (! $bodyIsHtml)
516   {
517     // try to remove the signature
518     if (($sp = strrpos($body, '-- ')) !== false && ($sp == 0 || $body{$sp-1} == "\n"))
519       {
520       if ($body{$sp+3}==' ' || $body{$sp+3}=="\n" || $body{$sp+3}=="\r")
521         $body = substr($body, 0, max(0, $sp-1));
522       }
523
524     // soft-wrap message first
525     $body = rcmail_wrap_quoted($body, 75);
526
527     $body = rtrim($body, "\r\n");
528
529     if ($body) {
530       // split body into single lines
531       $a_lines = preg_split('/\r?\n/', $body);
532
533       // add > to each line
534       for($n=0; $n<sizeof($a_lines); $n++) {
535         if (strpos($a_lines[$n], '>')===0)
536           $a_lines[$n] = '>'.$a_lines[$n];
537         else
538           $a_lines[$n] = '> '.$a_lines[$n];
539         }
540  
541       $body = join("\n", $a_lines);
542       }
543
544     // add title line(s)
545     $prefix = rc_wordwrap(sprintf("On %s, %s wrote:\n",
546       $MESSAGE->headers->date,
547       $MESSAGE->get_header('from')), 76);
548
549     $suffix = '';
550   }
551   else
552   {
553     // save inline images to files
554     $cid_map = rcmail_write_inline_attachments($MESSAGE);
555     // set is_safe flag (we need this for html body washing)
556     rcmail_check_safe($MESSAGE);
557     // clean up html tags
558     $body = rcmail_wash_html($body, array('safe' => $MESSAGE->is_safe), $cid_map);
559
560     // build reply (quote content)
561     $prefix = sprintf("On %s, %s wrote:<br />\n",
562       $MESSAGE->headers->date,
563       htmlspecialchars(Q($MESSAGE->get_header('from'), 'replace'), ENT_COMPAT, $OUTPUT->get_charset()));
564     $prefix .= '<blockquote type="cite" style="padding-left:5px; border-left:#1010ff 2px solid; margin-left:5px; width:100%">';
565     $suffix = "</blockquote><p></p>";
566   }
567
568   return $prefix.$body.$suffix;
569 }
570
571
572 function rcmail_create_forward_body($body, $bodyIsHtml)
573 {
574   global $IMAP, $MESSAGE, $OUTPUT;
575
576   // add attachments
577   if (!isset($_SESSION['compose']['forward_attachments']) && is_array($MESSAGE->mime_parts))
578     $cid_map = rcmail_write_compose_attachments($MESSAGE, $bodyIsHtml);
579
580   if (!$bodyIsHtml)
581   {
582     $prefix = "\n\n\n-------- Original Message --------\n";
583     $prefix .= 'Subject: ' . $MESSAGE->subject . "\n";
584     $prefix .= 'Date: ' . $MESSAGE->headers->date . "\n";
585     $prefix .= 'From: ' . $MESSAGE->get_header('from') . "\n";
586     $prefix .= 'To: ' . $MESSAGE->get_header('to') . "\n";
587     if ($MESSAGE->headers->replyto && $MESSAGE->headers->replyto != $MESSAGE->headers->from)
588       $prefix .= 'Reply-To: ' . $MESSAGE->get_header('replyto') . "\n";
589     $prefix .= "\n";
590   }
591   else
592   {
593     // set is_safe flag (we need this for html body washing)
594     rcmail_check_safe($MESSAGE);
595     // clean up html tags
596     $body = rcmail_wash_html($body, array('safe' => $MESSAGE->is_safe), $cid_map);
597
598     $prefix = sprintf(
599       "<br><br>-------- Original Message --------" .
600         "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\"><tbody>" .
601         "<tr><th align=\"right\" nowrap=\"nowrap\" valign=\"baseline\">Subject: </th><td>%s</td></tr>" .
602         "<tr><th align=\"right\" nowrap=\"nowrap\" valign=\"baseline\">Date: </th><td>%s</td></tr>" .
603         "<tr><th align=\"right\" nowrap=\"nowrap\" valign=\"baseline\">From: </th><td>%s</td></tr>" .
604         "<tr><th align=\"right\" nowrap=\"nowrap\" valign=\"baseline\">To: </th><td>%s</td></tr>",
605       Q($MESSAGE->subject),
606       Q($MESSAGE->headers->date),
607       htmlspecialchars(Q($MESSAGE->get_header('from'), 'replace'), ENT_COMPAT, $OUTPUT->get_charset()),
608       htmlspecialchars(Q($MESSAGE->get_header('to'), 'replace'), ENT_COMPAT, $OUTPUT->get_charset()));
609
610     if ($MESSAGE->headers->replyto && $MESSAGE->headers->replyto != $MESSAGE->headers->from)
611       $prefix .= sprintf("<tr><th align=\"right\" nowrap=\"nowrap\" valign=\"baseline\">Reply-To: </th><td>%s</td></tr>",
612         htmlspecialchars(Q($MESSAGE->get_header('replyto'), 'replace'), ENT_COMPAT, $OUTPUT->get_charset()));
613
614     $prefix .= "</tbody></table><br>";
615   }
616     
617   return $prefix.$body;
618 }
619
620
621 function rcmail_create_draft_body($body, $bodyIsHtml)
622 {
623   global $MESSAGE, $OUTPUT;
624   
625   /**
626    * add attachments
627    * sizeof($MESSAGE->mime_parts can be 1 - e.g. attachment, but no text!
628    */
629   if (empty($_SESSION['compose']['forward_attachments'])
630       && is_array($MESSAGE->mime_parts)
631       && count($MESSAGE->mime_parts) > 0)
632   {
633     $cid_map = rcmail_write_compose_attachments($MESSAGE, $bodyIsHtml);
634
635     // replace cid with href in inline images links
636     if ($cid_map)
637       $body = str_replace(array_keys($cid_map), array_values($cid_map), $body);
638   }
639   
640   return $body;
641 }
642   
643   
644 function rcmail_write_compose_attachments(&$message, $bodyIsHtml)
645 {
646   global $OUTPUT;
647
648   $cid_map = array();
649   foreach ((array)$message->mime_parts as $pid => $part)
650   {
651     if (($part->ctype_primary != 'message' || !$bodyIsHtml) && $part->ctype_primary != 'multipart' && 
652         ($part->disposition == 'attachment' || ($part->disposition == 'inline' && $bodyIsHtml) || $part->filename))
653     {
654       if ($attachment = rcmail_save_attachment($message, $pid)) {
655         $_SESSION['compose']['attachments'][$attachment['id']] = $attachment;
656         if ($bodyIsHtml && $part->content_id) {
657           $cid_map['cid:'.$part->content_id] = $OUTPUT->app->comm_path.'&_action=display-attachment&_file=rcmfile'.$attachment['id'];
658         }
659       }
660     }
661   }
662
663   $_SESSION['compose']['forward_attachments'] = true;
664
665   return $cid_map;
666 }
667
668
669 function rcmail_write_inline_attachments(&$message)
670 {
671   global $OUTPUT;
672
673   $cid_map = array();
674   foreach ((array)$message->mime_parts as $pid => $part) {
675     if ($part->content_id && $part->filename) {
676       if ($attachment = rcmail_save_attachment($message, $pid)) {
677         $_SESSION['compose']['attachments'][$attachment['id']] = $attachment;
678         $cid_map['cid:'.$part->content_id] = $OUTPUT->app->comm_path.'&_action=display-attachment&_file=rcmfile'.$attachment['id'];
679       }
680     }
681   }
682   
683   return $cid_map;
684 }
685
686 function rcmail_save_attachment(&$message, $pid)
687 {
688   $part = $message->mime_parts[$pid];
689   $mem_limit = parse_bytes(ini_get('memory_limit'));
690   $curr_mem = function_exists('memory_get_usage') ? memory_get_usage() : 16*1024*1024; // safe value: 16MB
691   $data = $path = null;
692
693   // don't load too big attachments into memory
694   if ($mem_limit > 0 && $part->size > $mem_limit - $curr_mem) {
695     $rcmail = rcmail::get_instance();
696     $temp_dir = unslashify($rcmail->config->get('temp_dir'));
697     $path = tempnam($temp_dir, 'rcmAttmnt');
698     if ($fp = fopen($path, 'w')) {
699       $message->get_part_content($pid, $fp);
700       fclose($fp);
701     } else
702       return false;
703   } else {
704     $data = $message->get_part_content($pid);
705   }
706
707   $attachment = array(
708     'name' => $part->filename ? $part->filename : 'Part_'.$pid.'.'.$part->ctype_secondary,
709     'mimetype' => $part->ctype_primary . '/' . $part->ctype_secondary,
710     'content_id' => $part->content_id,
711     'data' => $data,
712     'path' => $path
713   );
714   
715   $attachment = rcmail::get_instance()->plugins->exec_hook('save_attachment', $attachment);
716
717   if ($attachment['status']) {
718     unset($attachment['data'], $attachment['status'], $attachment['content_id'], $attachment['abort']);
719     return $attachment;
720   } else if ($path) {
721     @unlink($path);
722   }
723   
724   return false;
725 }
726
727
728 function rcmail_compose_subject($attrib)
729 {
730   global $MESSAGE, $compose_mode;
731   
732   list($form_start, $form_end) = get_form_tags($attrib);
733   unset($attrib['form']);
734   
735   $attrib['name'] = '_subject';
736   $attrib['spellcheck'] = 'true';
737   $textfield = new html_inputfield($attrib);
738
739   $subject = '';
740
741   // use subject from post
742   if (isset($_POST['_subject'])) {
743     $subject = get_input_value('_subject', RCUBE_INPUT_POST, TRUE);
744   }
745   // create a reply-subject
746   else if ($compose_mode == RCUBE_COMPOSE_REPLY) {
747     if (preg_match('/^re:/i', $MESSAGE->subject))
748       $subject = $MESSAGE->subject;
749     else
750       $subject = 'Re: '.$MESSAGE->subject;
751   }
752   // create a forward-subject
753   else if ($compose_mode == RCUBE_COMPOSE_FORWARD) {
754     if (preg_match('/^fwd:/i', $MESSAGE->subject))
755       $subject = $MESSAGE->subject;
756     else
757       $subject = 'Fwd: '.$MESSAGE->subject;
758   }
759   // creeate a draft-subject
760   else if ($compose_mode == RCUBE_COMPOSE_DRAFT || $compose_mode == RCUBE_COMPOSE_EDIT) {
761     $subject = $MESSAGE->subject;
762   }
763   else if (!empty($_SESSION['compose']['param']['subject'])) {
764     $subject = $_SESSION['compose']['param']['subject'];
765   }
766   
767   $out = $form_start ? "$form_start\n" : '';
768   $out .= $textfield->show($subject);
769   $out .= $form_end ? "\n$form_end" : '';
770          
771   return $out;
772 }
773
774
775 function rcmail_compose_attachment_list($attrib)
776 {
777   global $OUTPUT, $CONFIG;
778   
779   // add ID if not given
780   if (!$attrib['id'])
781     $attrib['id'] = 'rcmAttachmentList';
782   
783   $out = "\n";
784   
785   if (is_array($_SESSION['compose']['attachments']))
786   {
787     if ($attrib['deleteicon']) {
788       $button = html::img(array(
789         'src' => $CONFIG['skin_path'] . $attrib['deleteicon'],
790         'alt' => rcube_label('delete')
791       ));
792     }
793     else
794       $button = Q(rcube_label('delete'));
795
796     foreach ($_SESSION['compose']['attachments'] as $id => $a_prop)
797     {
798       if (empty($a_prop))
799         continue;
800       
801       $out .= html::tag('li', array('id' => "rcmfile".$id),
802         html::a(array(
803             'href' => "#delete",
804             'title' => rcube_label('delete'),
805             'onclick' => sprintf("return %s.command('remove-attachment','rcmfile%s', this)", JS_OBJECT_NAME, $id)),
806           $button) . Q($a_prop['name']));
807     }
808   }
809
810   if ($attrib['deleteicon'])
811     $_SESSION['compose']['deleteicon'] = $CONFIG['skin_path'] . $attrib['deleteicon'];
812
813   $OUTPUT->add_gui_object('attachmentlist', $attrib['id']);
814     
815   return html::tag('ul', $attrib, $out, html::$common_attrib);
816 }
817
818
819 function rcmail_compose_attachment_form($attrib)
820 {
821   global $OUTPUT;
822
823   // add ID if not given
824   if (!$attrib['id'])
825     $attrib['id'] = 'rcmUploadbox';
826   
827   $button = new html_inputfield(array('type' => 'button', 'class' => 'button'));
828   
829   $out = html::div($attrib,
830     $OUTPUT->form_tag(array('name' => 'form', 'method' => 'post', 'enctype' => 'multipart/form-data'),
831       html::div(null, rcmail_compose_attachment_field(array())) .
832       html::div('hint', rcube_label(array('name' => 'maxuploadsize', 'vars' => array('size' => show_bytes(parse_bytes(ini_get('upload_max_filesize'))))))) .
833       html::div('buttons',
834         $button->show(rcube_label('close'), array('onclick' => "document.getElementById('$attrib[id]').style.visibility='hidden'")) . ' ' .
835         $button->show(rcube_label('upload'), array('onclick' => JS_OBJECT_NAME . ".command('send-attachment', this.form)"))
836       )
837     )
838   );
839   
840   $OUTPUT->add_gui_object('uploadbox', $attrib['id']);
841   return $out;
842 }
843
844
845 function rcmail_compose_attachment_field($attrib)
846 {
847   $attrib['type'] = 'file';
848   $attrib['name'] = '_attachments[]';
849   $field = new html_inputfield($attrib);
850   return $field->show();
851 }
852
853
854 function rcmail_priority_selector($attrib)
855 {
856   global $MESSAGE;
857   
858   list($form_start, $form_end) = get_form_tags($attrib);
859   unset($attrib['form']);
860   
861   $attrib['name'] = '_priority';
862   $selector = new html_select($attrib);
863
864   $selector->add(array(rcube_label('lowest'),
865                        rcube_label('low'),
866                        rcube_label('normal'),
867                        rcube_label('high'),
868                        rcube_label('highest')),
869                  array(5, 4, 0, 2, 1));
870                  
871   if (isset($_POST['_priority']))
872     $sel = $_POST['_priority'];
873   else if (intval($MESSAGE->headers->priority) != 3)
874     $sel = intval($MESSAGE->headers->priority);
875   else
876     $sel = 0;
877
878   $out = $form_start ? "$form_start\n" : '';
879   $out .= $selector->show($sel);
880   $out .= $form_end ? "\n$form_end" : '';
881          
882   return $out;
883 }
884
885
886 function rcmail_receipt_checkbox($attrib)
887 {
888   global $MESSAGE, $compose_mode;
889   
890   list($form_start, $form_end) = get_form_tags($attrib);
891   unset($attrib['form']);
892   
893   if (!isset($attrib['id']))
894     $attrib['id'] = 'receipt';  
895
896   $attrib['name'] = '_receipt';
897   $attrib['value'] = '1';
898   $checkbox = new html_checkbox($attrib);
899
900   $out = $form_start ? "$form_start\n" : '';
901   $out .= $checkbox->show(in_array($compose_mode, array(RCUBE_COMPOSE_DRAFT, RCUBE_COMPOSE_EDIT))
902         && $MESSAGE->headers->mdn_to ? 1 : 0);
903   $out .= $form_end ? "\n$form_end" : '';
904
905   return $out;
906 }
907
908
909 function rcmail_editor_selector($attrib)
910 {
911   global $CONFIG, $MESSAGE, $compose_mode;
912
913   // determine whether HTML or plain text should be checked
914   if ($compose_mode)
915     $useHtml = (($CONFIG['htmleditor'] || $compose_mode == RCUBE_COMPOSE_DRAFT || $compose_mode == RCUBE_COMPOSE_EDIT)
916         && $MESSAGE->has_html_part());
917   else
918     $useHtml = $CONFIG['htmleditor'] ? true : false;
919
920   if (empty($attrib['editorid']))
921     $attrib['editorid'] = 'rcmComposeBody';
922
923   if (empty($attrib['name']))
924     $attrib['name'] = 'editorSelect';
925     
926   $attrib['onchange'] = "return rcmail_toggle_editor(this.value=='html', '".$attrib['editorid']."', '_is_html')";
927
928   $select = new html_select($attrib);
929
930   $select->add(Q(rcube_label('htmltoggle')), 'html');
931   $select->add(Q(rcube_label('plaintoggle')), 'plain');
932
933   return $select->show($useHtml ? 'html' : 'plain');
934
935   foreach ($choices as $value => $text)
936   {
937     $attrib['id'] = '_' . $value;
938     $attrib['value'] = $value;
939     $selector .= $radio->show($chosenvalue, $attrib) . html::label($attrib['id'], Q(rcube_label($text)));
940   }
941
942   return $selector;
943 }
944
945
946 function rcmail_store_target_selection($attrib)
947 {
948   $attrib['name'] = '_store_target';
949   $select = rcmail_mailbox_select(array_merge($attrib, array('noselection' => '- '.rcube_label('dontsave').' -')));
950   return $select->show(rcmail::get_instance()->config->get('sent_mbox'), $attrib);
951 }
952
953
954 function get_form_tags($attrib)
955 {
956   global $RCMAIL, $MESSAGE_FORM;
957
958   $form_start = '';
959   if (!strlen($MESSAGE_FORM))
960   {
961     $hiddenfields = new html_hiddenfield(array('name' => '_task', 'value' => $RCMAIL->task));
962     $hiddenfields->add(array('name' => '_action', 'value' => 'send'));
963
964     $form_start = empty($attrib['form']) ? $RCMAIL->output->form_tag(array('name' => "form", 'method' => "post")) : '';
965     $form_start .= $hiddenfields->show();
966   }
967     
968   $form_end = (strlen($MESSAGE_FORM) && !strlen($attrib['form'])) ? '</form>' : '';
969   $form_name = !empty($attrib['form']) ? $attrib['form'] : 'form';
970   
971   if (!strlen($MESSAGE_FORM))
972     $RCMAIL->output->add_gui_object('messageform', $form_name);
973   
974   $MESSAGE_FORM = $form_name;
975
976   return array($form_start, $form_end);
977 }
978
979
980 // register UI objects
981 $OUTPUT->add_handlers(array(
982   'composeheaders' => 'rcmail_compose_headers',
983   'composesubject' => 'rcmail_compose_subject',
984   'composebody' => 'rcmail_compose_body',
985   'composeattachmentlist' => 'rcmail_compose_attachment_list',
986   'composeattachmentform' => 'rcmail_compose_attachment_form',
987   'composeattachment' => 'rcmail_compose_attachment_field',
988   'priorityselector' => 'rcmail_priority_selector',
989   'editorselector' => 'rcmail_editor_selector',
990   'receiptcheckbox' => 'rcmail_receipt_checkbox',
991   'storetarget' => 'rcmail_store_target_selection',
992 ));
993
994 $OUTPUT->send('compose');
995
996 ?>