source: subversion/trunk/roundcubemail/program/steps/mail/sendmail.inc @ 5716

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