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

Last change on this file since 5842 was 5842, checked in by thomasb, 16 months ago

Allow plugins to overwrite the displayed confirmation message when saving a draft

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