]> git.donarmstrong.com Git - roundcube.git/blob - program/steps/mail/sendmail.inc
eed6081047febe71a17133ad4c8592eb99960a06
[roundcube.git] / program / steps / mail / sendmail.inc
1 <?php
2
3 /*
4  +-----------------------------------------------------------------------+
5  | program/steps/mail/sendmail.inc                                       |
6  |                                                                       |
7  | This file is part of the Roundcube Webmail client                     |
8  | Copyright (C) 2005-2010, Roundcube Dev. - Switzerland                 |
9  | Licensed under the GNU GPL                                            |
10  |                                                                       |
11  | PURPOSE:                                                              |
12  |   Compose a new mail message with all headers and attachments         |
13  |   and send it using the PEAR::Net_SMTP class or with PHP mail()       |
14  |                                                                       |
15  +-----------------------------------------------------------------------+
16  | Author: Thomas Bruederli <roundcube@gmail.com>                        |
17  +-----------------------------------------------------------------------+
18
19  $Id: sendmail.inc 4395 2011-01-06 11:48:11Z thomasb $
20
21 */
22
23 // remove all scripts and act as called in frame
24 $OUTPUT->reset();
25 $OUTPUT->framed = TRUE;
26
27 $savedraft = !empty($_POST['_draft']) ? true : false;
28
29 /****** checks ********/
30
31 if (!isset($_SESSION['compose']['id'])) {
32   raise_error(array('code' => 500, 'type' => 'php',
33     'file' => __FILE__, 'line' => __LINE__,
34     'message' => "Invalid compose ID"), true, false);
35
36   $OUTPUT->show_message('internalerror', 'error');
37   $OUTPUT->send('iframe');
38 }
39
40 if (!$savedraft) {
41   if (empty($_POST['_to']) && empty($_POST['_cc']) && empty($_POST['_bcc'])
42     && empty($_POST['_subject']) && $_POST['_message']) {
43     $OUTPUT->show_message('sendingfailed', 'error');
44     $OUTPUT->send('iframe');
45   }
46
47   if(!empty($CONFIG['sendmail_delay'])) {
48     $wait_sec = time() - intval($CONFIG['sendmail_delay']) - intval($CONFIG['last_message_time']);
49     if($wait_sec < 0) {
50       $OUTPUT->show_message('senttooquickly', 'error', array('sec' => $wait_sec * -1));
51       $OUTPUT->send('iframe');
52     }
53   }
54 }
55
56
57 /****** message sending functions ********/
58
59 // encrypt parts of the header
60 function rcmail_encrypt_header($what)
61 {
62   global $CONFIG, $RCMAIL;
63   if (!$CONFIG['http_received_header_encrypt']) {
64     return $what;
65   }
66   return $RCMAIL->encrypt($what);
67 }
68
69 // get identity record
70 function rcmail_get_identity($id)
71 {
72   global $USER, $OUTPUT;
73
74   if ($sql_arr = $USER->get_identity($id)) {
75     $out = $sql_arr;
76     $out['mailto'] = $sql_arr['email'];
77     $out['string'] = format_email_recipient($sql_arr['email'],
78       rcube_charset_convert($sql_arr['name'], RCMAIL_CHARSET, $OUTPUT->get_charset()));
79
80     return $out;
81   }
82
83   return FALSE;
84 }
85
86 /**
87  * go from this:
88  * <img src="http[s]://.../tiny_mce/plugins/emotions/images/smiley-cool.gif" border="0" alt="Cool" title="Cool" />
89  *
90  * to this:
91  *
92  * <img src="/path/on/server/.../tiny_mce/plugins/emotions/images/smiley-cool.gif" border="0" alt="Cool" title="Cool" />
93  * ...
94  */
95 function rcmail_fix_emoticon_paths(&$mime_message)
96 {
97   global $CONFIG;
98
99   $body = $mime_message->getHTMLBody();
100
101   // remove any null-byte characters before parsing
102   $body = preg_replace('/\x00/', '', $body);
103
104   $searchstr = 'program/js/tiny_mce/plugins/emotions/img/';
105   $offset = 0;
106
107   // keep track of added images, so they're only added once
108   $included_images = array();
109
110   if (preg_match_all('# src=[\'"]([^\'"]+)#', $body, $matches, PREG_OFFSET_CAPTURE)) {
111     foreach ($matches[1] as $m) {
112       // find emoticon image tags
113       if (preg_match('#'.$searchstr.'(.*)$#', $m[0], $imatches)) {
114         $image_name = $imatches[1];
115
116         // sanitize image name so resulting attachment doesn't leave images dir
117         $image_name = preg_replace('/[^a-zA-Z0-9_\.\-]/i', '', $image_name);
118         $img_file = INSTALL_PATH . '/' . $searchstr . $image_name;
119
120         if (! in_array($image_name, $included_images)) {
121           // add the image to the MIME message
122           if (! $mime_message->addHTMLImage($img_file, 'image/gif', '', true, $image_name))
123             $OUTPUT->show_message("emoticonerror", 'error');
124           array_push($included_images, $image_name);
125         }
126
127         $body = substr_replace($body, $img_file, $m[1] + $offset, strlen($m[0]));
128         $offset += strlen($img_file) - strlen($m[0]);
129       }
130     }
131   }
132
133   $mime_message->setHTMLBody($body);
134
135   return $body;
136 }
137
138 // parse email address input (and count addresses)
139 function rcmail_email_input_format($mailto, $count=false, $check=true)
140 {
141   global $EMAIL_FORMAT_ERROR, $RECIPIENT_COUNT;
142
143   $regexp = array('/[,;]\s*[\r\n]+/', '/[\r\n]+/', '/[,;]\s*$/m', '/;/', '/(\S{1})(<\S+@\S+>)/U');
144   $replace = array(', ', ', ', '', ',', '\\1 \\2');
145
146   // replace new lines and strip ending ', ', make address input more valid
147   $mailto = trim(preg_replace($regexp, $replace, $mailto));
148
149   $result = array();
150   $items = rcube_explode_quoted_string(',', $mailto);
151
152   foreach($items as $item) {
153     $item = trim($item);
154     // address in brackets without name (do nothing)
155     if (preg_match('/^<\S+@\S+>$/', $item)) {
156       $item = idn_to_ascii($item);
157       $result[] = $item;
158     // address without brackets and without name (add brackets)
159     } else if (preg_match('/^\S+@\S+$/', $item)) {
160       $item = idn_to_ascii($item);
161       $result[] = '<'.$item.'>';
162     // address with name (handle name)
163     } else if (preg_match('/\S+@\S+>*$/', $item, $matches)) {
164       $address = $matches[0];
165       $name = str_replace($address, '', $item);
166       $name = trim($name);
167       if ($name && ($name[0] != '"' || $name[strlen($name)-1] != '"')
168           && preg_match('/[\(\)\<\>\\\.\[\]@,;:"]/', $name)) {
169             $name = '"'.addcslashes($name, '"').'"';
170       }
171       $address = idn_to_ascii($address);
172       if (!preg_match('/^<\S+@\S+>$/', $address))
173         $address = '<'.$address.'>';
174
175       $result[] = $name.' '.$address;
176       $item = $address;
177     } else if (trim($item)) {
178       continue;
179     }
180
181     // check address format
182     $item = trim($item, '<>');
183     if ($item && $check && !check_email($item)) {
184       $EMAIL_FORMAT_ERROR = $item;
185       return;
186     }
187   }
188
189   if ($count) {
190     $RECIPIENT_COUNT += count($result);
191   }
192
193   return implode(', ', $result);
194 }
195
196
197 /****** compose message ********/
198
199 if (strlen($_POST['_draft_saveid']) > 3)
200   $olddraftmessageid = get_input_value('_draft_saveid', RCUBE_INPUT_POST);
201
202 $message_id = rcmail_gen_message_id();
203
204 // set default charset
205 $input_charset = $OUTPUT->get_charset();
206 $message_charset = isset($_POST['_charset']) ? $_POST['_charset'] : $input_charset;
207
208 $EMAIL_FORMAT_ERROR = NULL;
209 $RECIPIENT_COUNT = 0;
210
211 $mailto = rcmail_email_input_format(get_input_value('_to', RCUBE_INPUT_POST, TRUE, $message_charset), true);
212 $mailcc = rcmail_email_input_format(get_input_value('_cc', RCUBE_INPUT_POST, TRUE, $message_charset), true);
213 $mailbcc = rcmail_email_input_format(get_input_value('_bcc', RCUBE_INPUT_POST, TRUE, $message_charset), true);
214
215 if ($EMAIL_FORMAT_ERROR) {
216   $OUTPUT->show_message('emailformaterror', 'error', array('email' => $EMAIL_FORMAT_ERROR));
217   $OUTPUT->send('iframe');
218 }
219
220 if (empty($mailto) && !empty($mailcc)) {
221   $mailto = $mailcc;
222   $mailcc = null;
223 }
224 else if (empty($mailto))
225   $mailto = 'undisclosed-recipients:;';
226
227 // Get sender name and address...
228 $from = get_input_value('_from', RCUBE_INPUT_POST, true, $message_charset);
229 // ... from identity...
230 if (is_numeric($from)) {
231   if (is_array($identity_arr = rcmail_get_identity($from))) {
232     if ($identity_arr['mailto'])
233       $from = $identity_arr['mailto'];
234     if ($identity_arr['string'])
235       $from_string = $identity_arr['string'];
236   }
237   else {
238     $from = null;
239   }
240 }
241 // ... if there is no identity record, this might be a custom from
242 else if ($from_string = rcmail_email_input_format($from)) {
243   if (preg_match('/(\S+@\S+)/', $from_string, $m))
244     $from = trim($m[1], '<>');
245   else
246     $from = null;
247 }
248
249 if (!$from_string && $from)
250   $from_string = $from;
251
252 // compose headers array
253 $headers = array();
254
255 // if configured, the Received headers goes to top, for good measure
256 if ($CONFIG['http_received_header'])
257 {
258   $nldlm = "\r\n\t";
259   // FROM/VIA
260   $http_header = 'from ';
261   if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
262     $host = $_SERVER['HTTP_X_FORWARDED_FOR'];
263     $hostname = gethostbyaddr($host);
264     if ($CONFIG['http_received_header_encrypt']) {
265       $http_header .= rcmail_encrypt_header($hostname);
266       if ($host != $hostname)
267         $http_header .= ' ('. rcmail_encrypt_header($host) . ')';
268     } else {
269       $http_header .= (($host != $hostname) ? $hostname : '[' . $host . ']');
270       if ($host != $hostname)
271         $http_header .= ' (['. $host .'])';
272     }
273     $http_header .= $nldlm . ' via ';
274   }
275   $host = $_SERVER['REMOTE_ADDR'];
276   $hostname = gethostbyaddr($host);
277   if ($CONFIG['http_received_header_encrypt']) {
278     $http_header .= rcmail_encrypt_header($hostname);
279     if ($host != $hostname)
280       $http_header .= ' ('. rcmail_encrypt_header($host) . ')';
281   } else {
282     $http_header .= (($host != $hostname) ? $hostname : '[' . $host . ']');
283     if ($host != $hostname)
284       $http_header .= ' (['. $host .'])';
285   }
286   // BY
287   $http_header .= $nldlm . 'by ' . $_SERVER['HTTP_HOST'];
288   // WITH
289   $http_header .= $nldlm . 'with HTTP (' . $_SERVER['SERVER_PROTOCOL'] .
290       ' '.$_SERVER['REQUEST_METHOD'] . '); ' . date('r');
291   $http_header = wordwrap($http_header, 69, $nldlm);
292
293   $headers['Received'] = $http_header;
294 }
295
296 $headers['Date'] = rcmail_user_date();
297 $headers['From'] = rcube_charset_convert($from_string, RCMAIL_CHARSET, $message_charset);
298 $headers['To'] = $mailto;
299
300 // additional recipients
301 if (!empty($mailcc)) {
302   $headers['Cc'] = $mailcc;
303 }
304 if (!empty($mailbcc)) {
305   $headers['Bcc'] = $mailbcc;
306 }
307 if (!empty($identity_arr['bcc'])) {
308   $headers['Bcc'] = ($headers['Bcc'] ? $headers['Bcc'].', ' : '') . $identity_arr['bcc'];
309   $RECIPIENT_COUNT ++;
310 }
311
312 if (($max_recipients = (int) $RCMAIL->config->get('max_recipients')) > 0) {
313   if ($RECIPIENT_COUNT > $max_recipients) {
314     $OUTPUT->show_message('toomanyrecipients', 'error', array('max' => $max_recipients));
315     $OUTPUT->send('iframe');
316   }
317 }
318
319 // add subject
320 $headers['Subject'] = trim(get_input_value('_subject', RCUBE_INPUT_POST, TRUE, $message_charset));
321
322 if (!empty($identity_arr['organization'])) {
323   $headers['Organization'] = $identity_arr['organization'];
324 }
325 if (!empty($_POST['_replyto'])) {
326   $headers['Reply-To'] = rcmail_email_input_format(get_input_value('_replyto', RCUBE_INPUT_POST, TRUE, $message_charset));
327 }
328 else if (!empty($identity_arr['reply-to'])) {
329   $headers['Reply-To'] = rcmail_email_input_format($identity_arr['reply-to'], false, true);
330 }
331 if (!empty($headers['Reply-To'])) {
332   $headers['Mail-Reply-To'] = $headers['Reply-To'];
333 }
334 if (!empty($_POST['_followupto'])) {
335   $headers['Mail-Followup-To'] = rcmail_email_input_format(get_input_value('_followupto', RCUBE_INPUT_POST, TRUE, $message_charset));
336 }
337 if (!empty($_SESSION['compose']['reply_msgid'])) {
338   $headers['In-Reply-To'] = $_SESSION['compose']['reply_msgid'];
339 }
340
341 // remember reply/forward UIDs in special headers
342 if (!empty($_SESSION['compose']['reply_uid']) && $savedraft) {
343   $headers['X-Draft-Info'] = array('type' => 'reply', 'uid' => $_SESSION['compose']['reply_uid']);
344 }
345 else if (!empty($_SESSION['compose']['forward_uid']) && $savedraft) {
346   $headers['X-Draft-Info'] = array('type' => 'forward', 'uid' => $_SESSION['compose']['forward_uid']);
347 }
348
349 if (!empty($_SESSION['compose']['references'])) {
350   $headers['References'] = $_SESSION['compose']['references'];
351 }
352
353 if (!empty($_POST['_priority'])) {
354   $priority = intval($_POST['_priority']);
355   $a_priorities = array(1=>'highest', 2=>'high', 4=>'low', 5=>'lowest');
356   if ($str_priority = $a_priorities[$priority]) {
357     $headers['X-Priority'] = sprintf("%d (%s)", $priority, ucfirst($str_priority));
358   }
359 }
360
361 if (!empty($_POST['_receipt'])) {
362   $headers['Return-Receipt-To'] = $from_string;
363   $headers['Disposition-Notification-To'] = $from_string;
364 }
365
366 // additional headers
367 $headers['Message-ID'] = $message_id;
368 $headers['X-Sender'] = $from;
369
370 if (is_array($headers['X-Draft-Info'])) {
371   $headers['X-Draft-Info'] = rcmail_draftinfo_encode($headers['X-Draft-Info'] + array('folder' => $_SESSION['compose']['mailbox']));
372 }
373 if (!empty($CONFIG['useragent'])) {
374   $headers['User-Agent'] = $CONFIG['useragent'];
375 }
376
377 // exec hook for header checking and manipulation
378 $data = $RCMAIL->plugins->exec_hook('message_outgoing_headers', array('headers' => $headers));
379
380 // sending aborted by plugin
381 if ($data['abort'] && !$savedraft) {
382   $OUTPUT->show_message($data['message'] ? $data['message'] : 'sendingfailed');
383   $OUTPUT->send('iframe');
384 }
385 else
386   $headers = $data['headers'];
387
388
389 $isHtml = (bool) get_input_value('_is_html', RCUBE_INPUT_POST);
390
391 // fetch message body
392 $message_body = get_input_value('_message', RCUBE_INPUT_POST, TRUE, $message_charset);
393
394 if (!$savedraft) {
395   if ($isHtml) {
396     // remove signature's div ID
397     $message_body = preg_replace('/\s*id="_rc_sig"/', '', $message_body);
398
399     // add inline css for blockquotes
400     $bstyle = 'padding-left:5px; border-left:#1010ff 2px solid; margin-left:5px; width:100%';
401     $message_body = preg_replace('/<blockquote>/',
402       '<blockquote type="cite" style="'.$bstyle.'">', $message_body);
403
404     // append doctype and html/body wrappers
405     $message_body = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN">' .
406       "\r\n<html><body>\r\n" . $message_body;
407   }
408
409   // generic footer for all messages
410   if ($isHtml && !empty($CONFIG['generic_message_footer_html'])) {
411       $footer = file_get_contents(realpath($CONFIG['generic_message_footer_html']));
412       $footer = rcube_charset_convert($footer, RCMAIL_CHARSET, $message_charset);
413   }
414   else if (!empty($CONFIG['generic_message_footer'])) {
415     $footer = file_get_contents(realpath($CONFIG['generic_message_footer']));
416     $footer = rcube_charset_convert($footer, RCMAIL_CHARSET, $message_charset);
417     if ($isHtml)
418       $footer = '<pre>'.$footer.'</pre>';
419   }
420   if ($footer)
421     $message_body .= "\r\n" . $footer;
422   if ($isHtml)
423     $message_body .= "\r\n</body></html>\r\n";
424 }
425
426 // set line length for body wrapping
427 $LINE_LENGTH = $RCMAIL->config->get('line_length', 72);
428
429 // Since we can handle big messages with disk usage, we need more time to work
430 @set_time_limit(0);
431
432 // create PEAR::Mail_mime instance
433 $MAIL_MIME = new Mail_mime("\r\n");
434
435 // Check if we have enough memory to handle the message in it
436 // It's faster than using files, so we'll do this if we only can
437 if (is_array($_SESSION['compose']['attachments']) && $CONFIG['smtp_server']
438   && ($mem_limit = parse_bytes(ini_get('memory_limit'))))
439 {
440   $memory = function_exists('memory_get_usage') ? memory_get_usage() : 16*1024*1024; // safe value: 16MB
441
442   foreach ($_SESSION['compose']['attachments'] as $id => $attachment)
443     $memory += $attachment['size'];
444
445   // Yeah, Net_SMTP needs up to 12x more memory, 1.33 is for base64
446   if ($memory * 1.33 * 12 > $mem_limit)
447     $MAIL_MIME->setParam('delay_file_io', true);
448 }
449
450 // For HTML-formatted messages, construct the MIME message with both
451 // the HTML part and the plain-text part
452
453 if ($isHtml) {
454   $plugin = $RCMAIL->plugins->exec_hook('message_outgoing_body',
455     array('body' => $message_body, 'type' => 'html', 'message' => $MAIL_MIME));
456
457   $MAIL_MIME->setHTMLBody($plugin['body']);
458
459   // replace emoticons
460   $plugin['body'] = rcmail_replace_emoticons($plugin['body']);
461
462   // add a plain text version of the e-mail as an alternative part.
463   $h2t = new html2text($plugin['body'], false, true, 0);
464   $plainTextPart = rc_wordwrap($h2t->get_text(), $LINE_LENGTH, "\r\n");
465   $plainTextPart = wordwrap($plainTextPart, 998, "\r\n", true);
466   if (!$plainTextPart) {
467     // empty message body breaks attachment handling in drafts
468     $plainTextPart = "\r\n";
469   }
470   else {
471     // make sure all line endings are CRLF (#1486712)
472     $plainTextPart = preg_replace('/\r?\n/', "\r\n", $plainTextPart);
473   }
474
475   $plugin = $RCMAIL->plugins->exec_hook('message_outgoing_body',
476     array('body' => $plainTextPart, 'type' => 'alternative', 'message' => $MAIL_MIME));
477
478   $MAIL_MIME->setTXTBody($plugin['body']);
479
480   // look for "emoticon" images from TinyMCE and change their src paths to
481   // be file paths on the server instead of URL paths.
482   $message_body = rcmail_fix_emoticon_paths($MAIL_MIME);
483 }
484 else {
485   $plugin = $RCMAIL->plugins->exec_hook('message_outgoing_body',
486     array('body' => $message_body, 'type' => 'plain', 'message' => $MAIL_MIME));
487
488   $message_body = $plugin['body'];
489
490   // compose format=flowed content if enabled
491   if ($flowed = $RCMAIL->config->get('send_format_flowed', true))
492     $message_body = rcube_message::format_flowed($message_body, min($LINE_LENGTH+2, 79));
493   else
494     $message_body = rc_wordwrap($message_body, $LINE_LENGTH, "\r\n");
495
496   $message_body = wordwrap($message_body, 998, "\r\n", true);
497   if (!strlen($message_body)) { 
498     // empty message body breaks attachment handling in drafts 
499     $message_body = "\r\n"; 
500   }
501
502   $MAIL_MIME->setTXTBody($message_body, false, true);
503 }
504
505 // add stored attachments, if any
506 if (is_array($_SESSION['compose']['attachments']))
507 {
508   foreach ($_SESSION['compose']['attachments'] as $id => $attachment) {
509     // This hook retrieves the attachment contents from the file storage backend
510     $attachment = $RCMAIL->plugins->exec_hook('attachment_get', $attachment);
511
512     $dispurl = '/\ssrc\s*=\s*[\'"]*\S+display-attachment\S+file=rcmfile' . preg_quote($attachment['id']) . '[\s\'"]*/';
513     $message_body = $MAIL_MIME->getHTMLBody();
514     if ($isHtml && (preg_match($dispurl, $message_body) > 0)) {
515       $message_body = preg_replace($dispurl, ' src="'.$attachment['name'].'" ', $message_body);
516       $MAIL_MIME->setHTMLBody($message_body);
517
518       if ($attachment['data'])
519         $MAIL_MIME->addHTMLImage($attachment['data'], $attachment['mimetype'], $attachment['name'], false);
520       else
521         $MAIL_MIME->addHTMLImage($attachment['path'], $attachment['mimetype'], $attachment['name'], true);
522     }
523     else {
524       $ctype = str_replace('image/pjpeg', 'image/jpeg', $attachment['mimetype']); // #1484914
525       $file = $attachment['data'] ? $attachment['data'] : $attachment['path'];
526
527       // .eml attachments send inline
528       $MAIL_MIME->addAttachment($file,
529         $ctype,
530         $attachment['name'],
531         ($attachment['data'] ? false : true),
532         ($ctype == 'message/rfc822' ? '8bit' : 'base64'),
533         ($ctype == 'message/rfc822' ? 'inline' : 'attachment'),
534         '', '', '',
535         $CONFIG['mime_param_folding'] ? 'quoted-printable' : NULL,
536         $CONFIG['mime_param_folding'] == 2 ? 'quoted-printable' : NULL,
537         '', RCMAIL_CHARSET
538       );
539     }
540   }
541 }
542
543 // choose transfer encoding for plain/text body
544 if (preg_match('/[^\x00-\x7F]/', $MAIL_MIME->getTXTBody()))
545   $transfer_encoding = $RCMAIL->config->get('force_7bit') ? 'quoted-printable' : '8bit';
546 else
547   $transfer_encoding = '7bit';
548
549 // encoding settings for mail composing
550 $MAIL_MIME->setParam('text_encoding', $transfer_encoding);
551 $MAIL_MIME->setParam('html_encoding', 'quoted-printable');
552 $MAIL_MIME->setParam('head_encoding', 'quoted-printable');
553 $MAIL_MIME->setParam('head_charset', $message_charset);
554 $MAIL_MIME->setParam('html_charset', $message_charset);
555 $MAIL_MIME->setParam('text_charset', $message_charset . ($flowed ? ";\r\n format=flowed" : ''));
556
557 // encoding subject header with mb_encode provides better results with asian characters
558 if (function_exists('mb_encode_mimeheader')) {
559   mb_internal_encoding($message_charset);
560   $headers['Subject'] = mb_encode_mimeheader($headers['Subject'],
561     $message_charset, 'Q', "\r\n", 8);
562   mb_internal_encoding(RCMAIL_CHARSET);
563 }
564
565 // pass headers to message object
566 $MAIL_MIME->headers($headers);
567
568 // Begin SMTP Delivery Block
569 if (!$savedraft)
570 {
571   // check 'From' address (identity may be incomplete)
572   if (empty($from)) {
573     $OUTPUT->show_message('nofromaddress', 'error');
574     $OUTPUT->send('iframe');
575   }
576
577   // Handle Delivery Status Notification request
578   if (!empty($_POST['_dsn'])) {
579     $smtp_opts['dsn'] = true;
580   }
581
582   $sent = rcmail_deliver_message($MAIL_MIME, $from, $mailto,
583     $smtp_error, $mailbody_file, $smtp_opts);
584
585   // return to compose page if sending failed
586   if (!$sent)
587     {
588     // remove temp file
589     if ($mailbody_file) {
590       unlink($mailbody_file);
591       }
592
593     if ($smtp_error)
594       $OUTPUT->show_message($smtp_error['label'], 'error', $smtp_error['vars']); 
595     else
596       $OUTPUT->show_message('sendingfailed', 'error'); 
597     $OUTPUT->send('iframe');
598     }
599
600   // save message sent time
601   if (!empty($CONFIG['sendmail_delay']))
602     $RCMAIL->user->save_prefs(array('last_message_time' => time()));
603   
604   // set replied/forwarded flag
605   if ($_SESSION['compose']['reply_uid'])
606     $IMAP->set_flag($_SESSION['compose']['reply_uid'], 'ANSWERED', $_SESSION['compose']['mailbox']);
607   else if ($_SESSION['compose']['forward_uid'])
608     $IMAP->set_flag($_SESSION['compose']['forward_uid'], 'FORWARDED', $_SESSION['compose']['mailbox']);
609
610 } // End of SMTP Delivery Block
611
612
613 // Determine which folder to save message
614 if ($savedraft)
615   $store_target = $CONFIG['drafts_mbox'];
616 else    
617   $store_target = isset($_POST['_store_target']) ? get_input_value('_store_target', RCUBE_INPUT_POST) : $CONFIG['sent_mbox'];
618
619 if ($store_target)
620   {
621   // check if folder is subscribed
622   if ($IMAP->mailbox_exists($store_target, true))
623     $store_folder = true;
624   // folder may be existing but not subscribed (#1485241)
625   else if (!$IMAP->mailbox_exists($store_target))
626     $store_folder = $IMAP->create_mailbox($store_target, true);
627   else if ($IMAP->subscribe($store_target))
628     $store_folder = true;
629
630   // append message to sent box
631   if ($store_folder) {
632
633     // message body in file
634     if ($mailbody_file || $MAIL_MIME->getParam('delay_file_io')) {
635       $headers = $MAIL_MIME->txtHeaders();
636       
637       // file already created
638       if ($mailbody_file)
639         $msg = $mailbody_file;
640       else {
641         $temp_dir = $RCMAIL->config->get('temp_dir');
642         $mailbody_file = tempnam($temp_dir, 'rcmMsg');
643         if (!PEAR::isError($msg = $MAIL_MIME->saveMessageBody($mailbody_file)))
644           $msg = $mailbody_file;
645         }
646       }
647     else {
648       $msg = $MAIL_MIME->getMessage();
649       $headers = '';
650       }
651
652     if (PEAR::isError($msg))
653       raise_error(array('code' => 600, 'type' => 'php',
654             'file' => __FILE__, 'line' => __LINE__,
655             'message' => "Could not create message: ".$msg->getMessage()),
656             TRUE, FALSE);
657     else {
658       $saved = $IMAP->save_message($store_target, $msg, $headers, $mailbody_file ? true : false);
659       }
660
661     if ($mailbody_file) {
662       unlink($mailbody_file);
663       $mailbody_file = null;
664       }
665
666     // raise error if saving failed
667     if (!$saved) {
668       raise_error(array('code' => 800, 'type' => 'imap',
669             'file' => __FILE__, 'line' => __LINE__,
670             'message' => "Could not save message in $store_target"), TRUE, FALSE);
671     
672       if ($savedraft) {
673         $OUTPUT->show_message('errorsaving', 'error');
674         $OUTPUT->send('iframe');
675         }
676       }
677     }
678
679   if ($olddraftmessageid)
680     {
681     // delete previous saved draft
682     $a_deleteid = $IMAP->search_once($CONFIG['drafts_mbox'],
683         'HEADER Message-ID '.$olddraftmessageid, true);
684     $deleted = $IMAP->delete_message($a_deleteid, $CONFIG['drafts_mbox']);
685
686     // raise error if deletion of old draft failed
687     if (!$deleted)
688       raise_error(array('code' => 800, 'type' => 'imap',
689                 'file' => __FILE__, 'line' => __LINE__,
690                 'message' => "Could not delete message from ".$CONFIG['drafts_mbox']), TRUE, FALSE);
691     }
692   }
693 // remove temp file
694 else if ($mailbody_file) {
695   unlink($mailbody_file);
696   }
697
698
699 if ($savedraft)
700   {
701   $msgid = strtr($message_id, array('>' => '', '<' => ''));
702   
703   // remember new draft-uid
704   $draftuids = $IMAP->search_once($CONFIG['drafts_mbox'], 'HEADER Message-ID '.$msgid, true);
705   $_SESSION['compose']['param']['_draft_uid'] = $draftuids[0];
706
707   // display success
708   $OUTPUT->show_message('messagesaved', 'confirmation');
709
710   // update "_draft_saveid" and the "cmp_hash" to prevent "Unsaved changes" warning
711   $OUTPUT->command('set_draft_id', $msgid);
712   $OUTPUT->command('compose_field_hash', true);
713
714   // start the auto-save timer again
715   $OUTPUT->command('auto_save_start');
716
717   $OUTPUT->send('iframe');
718   }
719 else
720   {
721   rcmail_compose_cleanup();
722
723   if ($store_folder && !$saved)
724     $OUTPUT->command('sent_successfully', 'error', rcube_label('errorsavingsent'));
725   else
726     $OUTPUT->command('sent_successfully', 'confirmation', rcube_label('messagesent'));
727   $OUTPUT->send('iframe');
728   }
729
730