Thomas Bruederli
2014-01-16 2baeac116abef9d5bcb748c687577d16dce868a0
commit | author | age
4e17e6 1 <?php
T 2
3 /*
4  +-----------------------------------------------------------------------+
5  | program/steps/mail/sendmail.inc                                       |
6  |                                                                       |
e019f2 7  | This file is part of the Roundcube Webmail client                     |
0f16a0 8  | Copyright (C) 2005-2013, The Roundcube Dev Team                       |
7fe381 9  |                                                                       |
T 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.                     |
4e17e6 13  |                                                                       |
T 14  | PURPOSE:                                                              |
15  |   Compose a new mail message with all headers and attachments         |
e8f8fe 16  |   and send it using the PEAR::Net_SMTP class or with PHP mail()       |
4e17e6 17  |                                                                       |
T 18  +-----------------------------------------------------------------------+
19  | Author: Thomas Bruederli <roundcube@gmail.com>                        |
20  +-----------------------------------------------------------------------+
21 */
22
0b6c1c 23 // remove all scripts and act as called in frame
T 24 $OUTPUT->reset();
25 $OUTPUT->framed = TRUE;
26
0f16a0 27 $savedraft      = !empty($_POST['_draft']) ? true : false;
AM 28 $sendmail_delay = (int) $RCMAIL->config->get('sendmail_delay');
29 $drafts_mbox    = $RCMAIL->config->get('drafts_mbox');
acb08f 30
6b2b2e 31 $COMPOSE_ID = rcube_utils::get_input_value('_id', rcube_utils::INPUT_GPC);
72ff6a 32 $COMPOSE    =& $_SESSION['compose_data_'.$COMPOSE_ID];
4591de 33
acb08f 34 /****** checks ********/
0b6c1c 35
72ff6a 36 if (!isset($COMPOSE['id'])) {
0f16a0 37     rcube::raise_error(array('code' => 500, 'type' => 'php',
AM 38         'file' => __FILE__, 'line' => __LINE__,
39         'message' => "Invalid compose ID"), true, false);
10eedb 40
0f16a0 41     $OUTPUT->show_message('internalerror', 'error');
AM 42     $OUTPUT->send('iframe');
0b6c1c 43 }
4e17e6 44
4b60fa 45 if (!$savedraft) {
0f16a0 46     if (empty($_POST['_to']) && empty($_POST['_cc']) && empty($_POST['_bcc'])
AM 47         && empty($_POST['_subject']) && $_POST['_message']
48     ) {
49         $OUTPUT->show_message('sendingfailed', 'error');
50         $OUTPUT->send('iframe');
acb08f 51     }
0f16a0 52
AM 53     if ($sendmail_delay) {
54         $wait_sec = time() - $sendmail_delay - intval($RCMAIL->config->get('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     }
acb08f 60 }
A 61
4e17e6 62
acb08f 63 /****** compose message ********/
A 64
10936f 65 if (empty($COMPOSE['param']['message-id'])) {
0f16a0 66     $COMPOSE['param']['message-id'] = $RCMAIL->gen_message_id();
10936f 67 }
AM 68 $message_id = $COMPOSE['param']['message-id'];
4e17e6 69
5bc8cb 70 // set default charset
27be4e 71 $message_charset = isset($_POST['_charset']) ? $_POST['_charset'] : $OUTPUT->get_charset();
c03095 72
e4acbb 73 $EMAIL_FORMAT_ERROR = NULL;
0f16a0 74 $RECIPIENT_COUNT    = 0;
e4acbb 75
0f16a0 76 $mailto  = rcmail_email_input_format(rcube_utils::get_input_value('_to', rcube_utils::INPUT_POST, TRUE, $message_charset), true);
AM 77 $mailcc  = rcmail_email_input_format(rcube_utils::get_input_value('_cc', rcube_utils::INPUT_POST, TRUE, $message_charset), true);
6b2b2e 78 $mailbcc = rcmail_email_input_format(rcube_utils::get_input_value('_bcc', rcube_utils::INPUT_POST, TRUE, $message_charset), true);
4e17e6 79
e4acbb 80 if ($EMAIL_FORMAT_ERROR) {
0f16a0 81     $OUTPUT->show_message('emailformaterror', 'error', array('email' => $EMAIL_FORMAT_ERROR));
AM 82     $OUTPUT->send('iframe');
e4acbb 83 }
A 84
e8f8fe 85 if (empty($mailto) && !empty($mailcc)) {
0f16a0 86     $mailto = $mailcc;
AM 87     $mailcc = null;
e8f8fe 88 }
0f16a0 89 else if (empty($mailto)) {
AM 90     $mailto = 'undisclosed-recipients:;';
91 }
e8f8fe 92
d2b884 93 // Get sender name and address...
6b2b2e 94 $from = rcube_utils::get_input_value('_from', rcube_utils::INPUT_POST, true, $message_charset);
d2b884 95 // ... from identity...
A 96 if (is_numeric($from)) {
0f16a0 97     if (is_array($identity_arr = rcmail_get_identity($from))) {
AM 98         if ($identity_arr['mailto'])
99             $from = $identity_arr['mailto'];
100         if ($identity_arr['string'])
101             $from_string = $identity_arr['string'];
102     }
103     else {
104         $from = null;
105     }
d2b884 106 }
A 107 // ... if there is no identity record, this might be a custom from
108 else if ($from_string = rcmail_email_input_format($from)) {
0f16a0 109     if (preg_match('/(\S+@\S+)/', $from_string, $m))
AM 110         $from = trim($m[1], '<>');
111     else
112         $from = null;
d2b884 113 }
fd51e0 114
0f16a0 115 if (!$from_string && $from) {
AM 116     $from_string = $from;
117 }
4e17e6 118
T 119 // compose headers array
2471d3 120 $headers = array();
A 121
122 // if configured, the Received headers goes to top, for good measure
0f16a0 123 if ($RCMAIL->config->get('http_received_header')) {
AM 124     $nldlm   = "\r\n\t";
125     $encrypt = $RCMAIL->config->get('http_received_header_encrypt');
a520f3 126
0f16a0 127     // FROM/VIA
AM 128     $http_header = 'from ';
129
130     if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
131         $hosts    = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'], 2);
132         $hostname = gethostbyaddr($hosts[0]);
133
134         if ($encrypt) {
135             $http_header .= rcmail_encrypt_header($hostname);
136             if ($host != $hostname)
137                 $http_header .= ' ('. rcmail_encrypt_header($host) . ')';
138         }
139         else {
140             $http_header .= (($host != $hostname) ? $hostname : '[' . $host . ']');
141             if ($host != $hostname)
142                 $http_header .= ' (['. $host .'])';
143         }
144         $http_header .= $nldlm . ' via ';
ddc891 145     }
A 146
0f16a0 147     $host = $_SERVER['REMOTE_ADDR'];
AM 148     $hostname = gethostbyaddr($host);
149
150     if ($encrypt) {
151         $http_header .= rcmail_encrypt_header($hostname);
152         if ($host != $hostname)
153             $http_header .= ' ('. rcmail_encrypt_header($host) . ')';
154     }
155     else {
156         $http_header .= (($host != $hostname) ? $hostname : '[' . $host . ']');
157         if ($host != $hostname)
158             $http_header .= ' (['. $host .'])';
159     }
160
161     // BY
162     $http_header .= $nldlm . 'by ' . $_SERVER['HTTP_HOST'];
163
164     // WITH
165     $http_header .= $nldlm . 'with HTTP (' . $_SERVER['SERVER_PROTOCOL'] .
166       ' '.$_SERVER['REQUEST_METHOD'] . '); ' . date('r');
167     $http_header = wordwrap($http_header, 69, $nldlm);
168
169     $headers['Received'] = $http_header;
2471d3 170 }
A 171
6b2b2e 172 $headers['Date'] = $RCMAIL->user_date();
AM 173 $headers['From'] = rcube_charset::convert($from_string, RCUBE_CHARSET, $message_charset);
2471d3 174 $headers['To'] = $mailto;
4e17e6 175
T 176 // additional recipients
14f87f 177 if (!empty($mailcc)) {
0f16a0 178     $headers['Cc'] = $mailcc;
14f87f 179 }
A 180 if (!empty($mailbcc)) {
0f16a0 181     $headers['Bcc'] = $mailbcc;
14f87f 182 }
751b22 183
A 184 if (($max_recipients = (int) $RCMAIL->config->get('max_recipients')) > 0) {
0f16a0 185     if ($RECIPIENT_COUNT > $max_recipients) {
AM 186         $OUTPUT->show_message('toomanyrecipients', 'error', array('max' => $max_recipients));
187         $OUTPUT->send('iframe');
188     }
751b22 189 }
4e17e6 190
T 191 // add subject
6b2b2e 192 $headers['Subject'] = trim(rcube_utils::get_input_value('_subject', rcube_utils::INPUT_POST, TRUE, $message_charset));
4e17e6 193
14f87f 194 if (!empty($identity_arr['organization'])) {
0f16a0 195     $headers['Organization'] = $identity_arr['organization'];
3ee5a7 196 }
0f16a0 197 if ($hdr = rcube_utils::get_input_value('_replyto', rcube_utils::INPUT_POST, TRUE, $message_charset)) {
AM 198     $headers['Reply-To'] = rcmail_email_input_format($hdr);
14f87f 199 }
A 200 if (!empty($headers['Reply-To'])) {
0f16a0 201     $headers['Mail-Reply-To'] = $headers['Reply-To'];
14f87f 202 }
0f16a0 203 if ($hdr = rcube_utils::get_input_value('_followupto', rcube_utils::INPUT_POST, TRUE, $message_charset)) {
AM 204     $headers['Mail-Followup-To'] = rcmail_email_input_format();
14f87f 205 }
e99991 206
bbc856 207 // remember reply/forward UIDs in special headers
72ff6a 208 if (!empty($COMPOSE['reply_uid']) && $savedraft) {
0f16a0 209     $headers['X-Draft-Info'] = array('type' => 'reply', 'uid' => $COMPOSE['reply_uid']);
14f87f 210 }
72ff6a 211 else if (!empty($COMPOSE['forward_uid']) && $savedraft) {
0f16a0 212     $headers['X-Draft-Info'] = array('type' => 'forward', 'uid' => $COMPOSE['forward_uid']);
14f87f 213 }
bbc856 214
eafd5b 215 if (!empty($COMPOSE['reply_msgid'])) {
0f16a0 216     $headers['In-Reply-To'] = $COMPOSE['reply_msgid'];
eafd5b 217 }
72ff6a 218 if (!empty($COMPOSE['references'])) {
0f16a0 219     $headers['References'] = $COMPOSE['references'];
14f87f 220 }
4e17e6 221
d2b884 222 if (!empty($_POST['_priority'])) {
0f16a0 223     $priority     = intval($_POST['_priority']);
AM 224     $a_priorities = array(1 => 'highest', 2 => 'high', 4 => 'low', 5 => 'lowest');
225
226     if ($str_priority = $a_priorities[$priority]) {
227         $headers['X-Priority'] = sprintf("%d (%s)", $priority, ucfirst($str_priority));
228     }
d2b884 229 }
4e17e6 230
d2b884 231 if (!empty($_POST['_receipt'])) {
0f16a0 232     $headers['Return-Receipt-To']           = $from_string;
AM 233     $headers['Disposition-Notification-To'] = $from_string;
d2b884 234 }
4e17e6 235
T 236 // additional headers
53e79d 237 $headers['Message-ID'] = $message_id;
0f16a0 238 $headers['X-Sender']   = $from;
53e79d 239
14f87f 240 if (is_array($headers['X-Draft-Info'])) {
0f16a0 241     $headers['X-Draft-Info'] = rcmail_draftinfo_encode($headers['X-Draft-Info'] + array('folder' => $COMPOSE['mailbox']));
14f87f 242 }
0f16a0 243 if ($hdr = $RCMAIL->config->get('useragent')) {
AM 244     $headers['User-Agent'] = $hdr;
14f87f 245 }
4e17e6 246
b44b4d 247 // exec hook for header checking and manipulation
6efadf 248 // Depracated: use message_before_send hook instead
e6ce00 249 $data = $RCMAIL->plugins->exec_hook('message_outgoing_headers', array('headers' => $headers));
b44b4d 250
T 251 // sending aborted by plugin
252 if ($data['abort'] && !$savedraft) {
0f16a0 253     $OUTPUT->show_message($data['message'] ? $data['message'] : 'sendingfailed');
AM 254     $OUTPUT->send('iframe');
b44b4d 255 }
0f16a0 256 else {
AM 257     $headers = $data['headers'];
258 }
b44b4d 259
6b2b2e 260 $isHtml = (bool) rcube_utils::get_input_value('_is_html', rcube_utils::INPUT_POST);
940fc1 261
c03095 262 // fetch message body
6b2b2e 263 $message_body = rcube_utils::get_input_value('_message', rcube_utils::INPUT_POST, TRUE, $message_charset);
940fc1 264
7e263e 265 if ($isHtml) {
0f16a0 266     $bstyle = array();
f7b2bf 267
0f16a0 268     if ($font_size = $RCMAIL->config->get('default_font_size')) {
AM 269         $bstyle[] = 'font-size: ' . $font_size;
270     }
271     if ($font_family = $RCMAIL->config->get('default_font')) {
272         $bstyle[] = 'font-family: ' . rcmail::font_defs($font_family);
273     }
7e263e 274
0f16a0 275     // append doctype and html/body wrappers
AM 276     $message_body = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN">'
277         . "\r\n<html><body" . (!empty($bstyle) ? " style='" . implode($bstyle, '; ') . "'" : '') . ">\r\n"
278         . $message_body;
7e263e 279 }
A 280
65605c 281 if (!$savedraft) {
0f16a0 282     if ($isHtml) {
AM 283         // remove signature's div ID
284         $message_body = preg_replace('/\s*id="_rc_sig"/', '', $message_body);
4e17e6 285
0f16a0 286         // add inline css for blockquotes
AM 287         $bstyle       = 'padding-left:5px; border-left:#1010ff 2px solid; margin-left:5px';
288         $message_body = preg_replace('/<blockquote>/',
289             '<blockquote type="cite" style="'.$bstyle.'">', $message_body);
1d5779 290     }
A 291
0f16a0 292     // Check spelling before send
AM 293     if ($RCMAIL->config->get('spellcheck_before_send') && $RCMAIL->config->get('enable_spellcheck')
294         && empty($COMPOSE['spell_checked']) && !empty($message_body)
295     ) {
296         $message_body = str_replace("\r\n", "\n", $message_body);
297         $spellchecker = new rcube_spellchecker(rcube_utils::get_input_value('_lang', rcube_utils::INPUT_GPC));
298         $spell_result = $spellchecker->check($message_body, $isHtml);
299
300         $COMPOSE['spell_checked'] = true;
301
302         if (!$spell_result) {
303             $result = $isHtml ? $spellchecker->get_words() : $spellchecker->get_xml();
304
305             $OUTPUT->show_message('mispellingsfound', 'error');
306             $OUTPUT->command('spellcheck_resume', $isHtml, $result);
307             $OUTPUT->send('iframe');
308         }
309     }
310
311     // generic footer for all messages
312     if ($footer = rcmail_generic_message_footer($isHtml)) {
313         $footer = rcube_charset::convert($footer, RCUBE_CHARSET, $message_charset);
314         $message_body .= "\r\n" . $footer;
315     }
7e263e 316 }
A 317
318 if ($isHtml) {
0f16a0 319     $message_body .= "\r\n</body></html>\r\n";
65605c 320 }
a0109c 321
b169de 322 // sort attachments to make sure the order is the same as in the UI (#1488423)
0f16a0 323 if ($files = rcube_utils::get_input_value('_attachments', rcube_utils::INPUT_POST)) {
AM 324     $files = explode(',', $files);
325     $files = array_flip($files);
326     foreach ($files as $idx => $val) {
327         $files[$idx] = $COMPOSE['attachments'][$idx];
328         unset($COMPOSE['attachments'][$idx]);
329     }
b169de 330
0f16a0 331     $COMPOSE['attachments'] = array_merge(array_filter($files), $COMPOSE['attachments']);
b169de 332 }
AM 333
b62049 334 // set line length for body wrapping
c769c6 335 $LINE_LENGTH = $RCMAIL->config->get('line_length', 72);
b62049 336
91790e 337 // Since we can handle big messages with disk usage, we need more time to work
A 338 @set_time_limit(0);
339
340 // create PEAR::Mail_mime instance
ac8edb 341 $MAIL_MIME = new Mail_mime("\r\n");
91790e 342
A 343 // Check if we have enough memory to handle the message in it
344 // It's faster than using files, so we'll do this if we only can
0f16a0 345 if (is_array($COMPOSE['attachments']) && $RCMAIL->config->get('smtp_server')
AM 346   && ($mem_limit = parse_bytes(ini_get('memory_limit')))
347 ) {
348     $memory = 0;
349     foreach ($COMPOSE['attachments'] as $id => $attachment) {
350         $memory += $attachment['size'];
351     }
91790e 352
0f16a0 353     // Yeah, Net_SMTP needs up to 12x more memory, 1.33 is for base64
AM 354     if (!rcube_utils::mem_check($memory * 1.33 * 12)) {
355         $MAIL_MIME->setParam('delay_file_io', true);
356     }
91790e 357 }
a0109c 358
S 359 // For HTML-formatted messages, construct the MIME message with both
360 // the HTML part and the plain-text part
cc97ea 361 if ($isHtml) {
0f16a0 362     $plugin = $RCMAIL->plugins->exec_hook('message_outgoing_body',
AM 363         array('body' => $message_body, 'type' => 'html', 'message' => $MAIL_MIME));
ac8edb 364
0f16a0 365     $MAIL_MIME->setHTMLBody($plugin['body']);
a0109c 366
0f16a0 367     // replace emoticons
AM 368     $plugin['body'] = $RCMAIL->replace_emoticons($plugin['body']);
747289 369
0f16a0 370     // add a plain text version of the e-mail as an alternative part.
AM 371     $h2t = new rcube_html2text($plugin['body'], false, true, 0, $message_charset);
372     $plainTextPart = rcube_mime::wordwrap($h2t->get_text(), $LINE_LENGTH, "\r\n", false, $message_charset);
373     $plainTextPart = wordwrap($plainTextPart, 998, "\r\n", true);
21d463 374
0f16a0 375     // make sure all line endings are CRLF (#1486712)
AM 376     $plainTextPart = preg_replace('/\r?\n/', "\r\n", $plainTextPart);
ac8edb 377
0f16a0 378     $plugin = $RCMAIL->plugins->exec_hook('message_outgoing_body',
AM 379         array('body' => $plainTextPart, 'type' => 'alternative', 'message' => $MAIL_MIME));
ac8edb 380
0f16a0 381     $MAIL_MIME->setTXTBody($plugin['body']);
a0109c 382
0f16a0 383     // look for "emoticon" images from TinyMCE and change their src paths to
AM 384     // be file paths on the server instead of URL paths.
385     rcmail_fix_emoticon_paths($MAIL_MIME);
9287ed 386
0f16a0 387     // Extract image Data URIs into message attachments (#1488502)
AM 388     rcmail_extract_inline_images($MAIL_MIME, $from);
cc97ea 389 }
6b6f2e 390 else {
0f16a0 391     $plugin = $RCMAIL->plugins->exec_hook('message_outgoing_body',
AM 392         array('body' => $message_body, 'type' => 'plain', 'message' => $MAIL_MIME));
5852c1 393
0f16a0 394     $message_body = $plugin['body'];
5852c1 395
0f16a0 396     // compose format=flowed content if enabled
AM 397     if ($flowed = ($savedraft || $RCMAIL->config->get('send_format_flowed', true)))
398         $message_body = rcube_mime::format_flowed($message_body, min($LINE_LENGTH+2, 79), $message_charset);
399     else
400         $message_body = rcube_mime::wordwrap($message_body, $LINE_LENGTH, "\r\n", false, $message_charset);
5852c1 401
0f16a0 402     $message_body = wordwrap($message_body, 998, "\r\n", true);
ac8edb 403
0f16a0 404     $MAIL_MIME->setTXTBody($message_body, false, true);
cc97ea 405 }
4e17e6 406
T 407 // add stored attachments, if any
e28b12 408 if (is_array($COMPOSE['attachments'])) {
0f16a0 409     foreach ($COMPOSE['attachments'] as $id => $attachment) {
AM 410         // This hook retrieves the attachment contents from the file storage backend
411         $attachment = $RCMAIL->plugins->exec_hook('attachment_get', $attachment);
cc97ea 412
0f16a0 413         if ($isHtml) {
AM 414             $dispurl      = '/\ssrc\s*=\s*[\'"]*\S+display-attachment\S+file=rcmfile'
415                 . preg_quote($attachment['id']) . '[\s\'"]*/';
416             $message_body = $MAIL_MIME->getHTMLBody();
417             $is_inline    = preg_match($dispurl, $message_body);
418         }
419         else {
420             $is_inline = false;
421         }
422
423         // inline image
424         if ($is_inline) {
425             // Mail_Mime does not support many inline attachments with the same name (#1489406)
426             // we'll generate cid: urls here to workaround this
427             $cid = preg_replace('/[^0-9a-zA-Z]/', '', uniqid(time(), true));
428             if (preg_match('#(@[0-9a-zA-Z\-\.]+)#', $from, $matches)) {
429                 $cid .= $matches[1];
430             }
431             else {
432                 $cid .= '@localhost';
433             }
434
435             $message_body = preg_replace($dispurl, ' src="cid:' . $cid . '" ', $message_body);
436
437             $MAIL_MIME->setHTMLBody($message_body);
438
439             if ($attachment['data'])
440                 $MAIL_MIME->addHTMLImage($attachment['data'], $attachment['mimetype'], $attachment['name'], false, $cid);
441             else
442                 $MAIL_MIME->addHTMLImage($attachment['path'], $attachment['mimetype'], $attachment['name'], true, $cid);
443         }
444         else {
445             $ctype   = str_replace('image/pjpeg', 'image/jpeg', $attachment['mimetype']); // #1484914
446             $file    = $attachment['data'] ? $attachment['data'] : $attachment['path'];
447             $folding = (int) $RCMAIL->config->get('mime_param_folding');
448
449             $MAIL_MIME->addAttachment($file,
450                 $ctype,
451                 $attachment['name'],
452                 $attachment['data'] ? false : true,
453                 $ctype == 'message/rfc822' ? '8bit' : 'base64',
454                 'attachment',
455                 '', '', '',
456                 $folding ? 'quoted-printable' : NULL,
457                 $folding == 2 ? 'quoted-printable' : NULL,
458                 '', RCUBE_CHARSET
459             );
460         }
e28b12 461     }
cc97ea 462 }
4e17e6 463
3d0ec7 464 // choose transfer encoding for plain/text body
ac3cdd 465 if (preg_match('/[^\x00-\x7F]/', $MAIL_MIME->getTXTBody())) {
0f16a0 466     $text_charset      = $message_charset;
AM 467     $transfer_encoding = $RCMAIL->config->get('force_7bit') ? 'quoted-printable' : '8bit';
ac3cdd 468 }
AM 469 else {
0f16a0 470     $text_charset      = '';
AM 471     $transfer_encoding = '7bit';
ac3cdd 472 }
AM 473
474 if ($flowed) {
0f16a0 475     if (!$text_charset) {
AM 476         $text_charset = 'US-ASCII';
477     }
ac3cdd 478
0f16a0 479     $text_charset .= ";\r\n format=flowed";
ac3cdd 480 }
3d0ec7 481
a95e0e 482 // encoding settings for mail composing
91790e 483 $MAIL_MIME->setParam('text_encoding', $transfer_encoding);
A 484 $MAIL_MIME->setParam('html_encoding', 'quoted-printable');
485 $MAIL_MIME->setParam('head_encoding', 'quoted-printable');
486 $MAIL_MIME->setParam('head_charset', $message_charset);
487 $MAIL_MIME->setParam('html_charset', $message_charset);
ac3cdd 488 $MAIL_MIME->setParam('text_charset', $text_charset);
cc97ea 489
5a6ad2 490 // encoding subject header with mb_encode provides better results with asian characters
d2b884 491 if (function_exists('mb_encode_mimeheader')) {
0f16a0 492     mb_internal_encoding($message_charset);
AM 493     $headers['Subject'] = mb_encode_mimeheader($headers['Subject'],
494         $message_charset, 'Q', "\r\n", 8);
495     mb_internal_encoding(RCUBE_CHARSET);
b517af 496 }
4e17e6 497
fba1f5 498 // pass headers to message object
T 499 $MAIL_MIME->headers($headers);
4e17e6 500
d2b884 501 // Begin SMTP Delivery Block
0f16a0 502 if (!$savedraft) {
AM 503     // check 'From' address (identity may be incomplete)
504     if (empty($from)) {
505         $OUTPUT->show_message('nofromaddress', 'error');
506         $OUTPUT->send('iframe');
e04e31 507     }
91790e 508
0f16a0 509     // Handle Delivery Status Notification request
AM 510     if (!empty($_POST['_dsn'])) {
511         $smtp_opts['dsn'] = true;
512     }
acb08f 513
0f16a0 514     $sent = $RCMAIL->deliver_message($MAIL_MIME, $from, $mailto,
AM 515         $smtp_error, $mailbody_file, $smtp_opts);
765fde 516
0f16a0 517     // return to compose page if sending failed
AM 518     if (!$sent) {
519         // remove temp file
520         if ($mailbody_file) {
521             unlink($mailbody_file);
522         }
c03095 523
0f16a0 524         if ($smtp_error)
AM 525             $OUTPUT->show_message($smtp_error['label'], 'error', $smtp_error['vars']); 
526         else
527             $OUTPUT->show_message('sendingfailed', 'error'); 
528         $OUTPUT->send('iframe');
529     }
41fa0b 530
0f16a0 531     // save message sent time
AM 532     if ($sendmail_delay) {
533         $RCMAIL->user->save_prefs(array('last_message_time' => time()));
534     }
535
536     // set replied/forwarded flag
537     if ($COMPOSE['reply_uid'])
538         $RCMAIL->storage->set_flag($COMPOSE['reply_uid'], 'ANSWERED', $COMPOSE['mailbox']);
539     else if ($COMPOSE['forward_uid'])
540         $RCMAIL->storage->set_flag($COMPOSE['forward_uid'], 'FORWARDED', $COMPOSE['mailbox']);
541 }
41fa0b 542
1966c5 543 // Determine which folder to save message
0f16a0 544 if ($savedraft) {
AM 545     $store_target = $drafts_mbox;
546 }
547 else if (!$RCMAIL->config->get('no_save_sent_messages')) {
548     $store_target = rcube_utils::get_input_value('_store_target', rcube_utils::INPUT_POST);
549     if (!strlen($store_target)) {
550         $sore_target = $RCMAIL->config->get('sent_mbox');
551     }
552 }
c03095 553
56ec81 554 if ($store_target) {
0f16a0 555     // check if folder is subscribed
AM 556     if ($RCMAIL->storage->folder_exists($store_target, true)) {
557         $store_folder = true;
56ec81 558     }
0f16a0 559     // folder may be existing but not subscribed (#1485241)
AM 560     else if (!$RCMAIL->storage->folder_exists($store_target)) {
561         $store_folder = $RCMAIL->storage->create_folder($store_target, true);
562     }
563     else if ($RCMAIL->storage->subscribe($store_target)) {
564         $store_folder = true;
56ec81 565     }
91790e 566
0f16a0 567     // append message to sent box
AM 568     if ($store_folder) {
569         // message body in file
570         if ($mailbody_file || $MAIL_MIME->getParam('delay_file_io')) {
571             $headers = $MAIL_MIME->txtHeaders();
572
573             // file already created
574             if ($mailbody_file) {
575                 $msg = $mailbody_file;
576             }
577             else {
578                 $temp_dir      = $RCMAIL->config->get('temp_dir');
579                 $mailbody_file = tempnam($temp_dir, 'rcmMsg');
580
581                 if (!PEAR::isError($msg = $MAIL_MIME->saveMessageBody($mailbody_file))) {
582                     $msg = $mailbody_file;
583                 }
584             }
585         }
586         else {
587             $msg     = $MAIL_MIME->getMessage();
588             $headers = '';
589         }
590
591         if (PEAR::isError($msg)) {
592             rcube::raise_error(array('code' => 650, 'type' => 'php',
593                 'file' => __FILE__, 'line' => __LINE__,
594                 'message' => "Could not create message: ".$msg->getMessage()),
595                 true, false);
596         }
597         else {
598             $saved = $RCMAIL->storage->save_message($store_target, $msg, $headers,
599                 $mailbody_file ? true : false, array('SEEN'));
600         }
601
602         if ($mailbody_file) {
603             unlink($mailbody_file);
604             $mailbody_file = null;
605         }
56ec81 606     }
91790e 607
0f16a0 608     // raise error if saving failed
AM 609     if (!$saved) {
610         rcube::raise_error(array('code' => 800, 'type' => 'imap',
611             'file' => __FILE__, 'line' => __LINE__,
612             'message' => "Could not save message in $store_target"), true, false);
613
614         if ($savedraft) {
615             $OUTPUT->show_message('errorsaving', 'error');
616             // start the auto-save timer again
617             $OUTPUT->command('auto_save_start');
618             $OUTPUT->send('iframe');
619         }
56ec81 620     }
91790e 621
1966c5 622     // delete previous saved draft
0f16a0 623     if ($saved && ($old_id = rcube_utils::get_input_value('_draft_saveid', rcube_utils::INPUT_POST))) {
AM 624         $deleted = $RCMAIL->storage->delete_message($old_id, $drafts_mbox);
4e17e6 625
0f16a0 626         // raise error if deletion of old draft failed
AM 627         if (!$deleted) {
628             rcube::raise_error(array('code' => 800, 'type' => 'imap',
629                 'file' => __FILE__, 'line' => __LINE__,
630                 'message' => "Could not delete message from $drafts_mbox"), true, false);
631         }
632     }
56ec81 633 }
91790e 634 // remove temp file
A 635 else if ($mailbody_file) {
0f16a0 636     unlink($mailbody_file);
56ec81 637 }
91790e 638
4e17e6 639
56ec81 640 if ($savedraft) {
0f16a0 641     // remember new draft-uid ($saved could be an UID or true/false here)
AM 642     if ($saved && is_bool($saved)) {
643         $index = $RCMAIL->storage->search_once($drafts_mbox, 'HEADER Message-ID ' . $message_id);
644         $saved = @max($index->get());
645     }
c719f3 646
0f16a0 647     if ($saved) {
AM 648         $plugin = $RCMAIL->plugins->exec_hook('message_draftsaved',
649             array('msgid' => $message_id, 'uid' => $saved, 'folder' => $store_target));
f0f98f 650
0f16a0 651         // display success
AM 652         $OUTPUT->show_message($plugin['message'] ? $plugin['message'] : 'messagesaved', 'confirmation');
10936f 653
0f16a0 654         // update "_draft_saveid" and the "cmp_hash" to prevent "Unsaved changes" warning
AM 655         $COMPOSE['param']['draft_uid'] = $plugin['uid'];
656         $OUTPUT->command('set_draft_id', $plugin['uid']);
657         $OUTPUT->command('compose_field_hash', true);
658     }
41fa0b 659
0f16a0 660     // start the auto-save timer again
AM 661     $OUTPUT->command('auto_save_start');
56ec81 662 }
A 663 else {
0f16a0 664     $folders = array();
66a549 665
0f16a0 666     if ($COMPOSE['mode'] == 'reply' || $COMPOSE['mode'] == 'forward') {
AM 667         $folders[] = $COMPOSE['mailbox'];
668     }
66a549 669
0f16a0 670     rcmail_compose_cleanup($COMPOSE_ID);
AM 671     $OUTPUT->command('remove_compose_data', $COMPOSE_ID);
9a5762 672
0f16a0 673     if ($store_folder && !$saved) {
AM 674         $OUTPUT->command('sent_successfully', 'error', $RCMAIL->gettext('errorsavingsent'), $folders);
675     }
676     else if ($store_folder) {
677         $folders[] = $store_target;
66a549 678     }
AM 679
6b2b2e 680     $OUTPUT->command('sent_successfully', 'confirmation', $RCMAIL->gettext('messagesent'), $folders);
56ec81 681 }
66a549 682
AM 683 $OUTPUT->send('iframe');
f5d2ee 684
AM 685
686 /****** message sending functions ********/
687
688 // encrypt parts of the header
689 function rcmail_encrypt_header($what)
690 {
691     global $RCMAIL;
692
693     if (!$RCMAIL->config->get('http_received_header_encrypt')) {
694         return $what;
695     }
696
697     return $RCMAIL->encrypt($what);
698 }
699
700 // get identity record
701 function rcmail_get_identity($id)
702 {
703     global $RCMAIL, $message_charset;
704
705     if ($sql_arr = $RCMAIL->user->get_identity($id)) {
706         $out = $sql_arr;
707
708         if ($message_charset != RCUBE_CHARSET) {
709             foreach ($out as $k => $v) {
710                 $out[$k] = rcube_charset::convert($v, RCUBE_CHARSET, $message_charset);
711             }
712         }
713
714         $out['mailto'] = $sql_arr['email'];
715         $out['string'] = format_email_recipient($sql_arr['email'], $sql_arr['name']);
716
717         return $out;
718     }
719
720     return false;
721 }
722
723 /**
724  * go from this:
725  * <img src="http[s]://.../tiny_mce/plugins/emotions/images/smiley-cool.gif" border="0" alt="Cool" title="Cool" />
726  *
727  * to this:
728  *
729  * <img src="/path/on/server/.../tiny_mce/plugins/emotions/images/smiley-cool.gif" border="0" alt="Cool" title="Cool" />
730  */
731 function rcmail_fix_emoticon_paths($mime_message)
732 {
733     global $RCMAIL;
734
735     $body = $mime_message->getHTMLBody();
736
737     // remove any null-byte characters before parsing
738     $body = preg_replace('/\x00/', '', $body);
739
740     $searchstr = 'program/js/tiny_mce/plugins/emotions/img/';
741     $offset = 0;
742
743     // keep track of added images, so they're only added once
744     $included_images = array();
745
746     if (preg_match_all('# src=[\'"]([^\'"]+)#', $body, $matches, PREG_OFFSET_CAPTURE)) {
747         foreach ($matches[1] as $m) {
748             // find emoticon image tags
749             if (preg_match('#'.$searchstr.'(.*)$#', $m[0], $imatches)) {
750                 $image_name = $imatches[1];
751
752                 // sanitize image name so resulting attachment doesn't leave images dir
753                 $image_name = preg_replace('/[^a-zA-Z0-9_\.\-]/i', '', $image_name);
754                 $img_file   = INSTALL_PATH . '/' . $searchstr . $image_name;
755
756                 if (! in_array($image_name, $included_images)) {
757                     // add the image to the MIME message
758                     if (!$mime_message->addHTMLImage($img_file, 'image/gif', '', true, $image_name)) {
759                         $RCMAIL->output->show_message("emoticonerror", 'error');
760                     }
761
762                     array_push($included_images, $image_name);
763                 }
764
765                 $body    = substr_replace($body, $img_file, $m[1] + $offset, strlen($m[0]));
766                 $offset += strlen($img_file) - strlen($m[0]);
767             }
768         }
769     }
770
771     $mime_message->setHTMLBody($body);
772 }
773
774 /**
775  * Extract image attachments from HTML content (data URIs)
776  */
777 function rcmail_extract_inline_images($mime_message, $from)
778 {
779     $body   = $mime_message->getHTMLBody();
780     $offset = 0;
781     $list   = array();
14bd92 782     $domain = 'localhost';
AM 783     $regexp = '#img[^>]+src=[\'"](data:([^;]*);base64,([a-z0-9+/=\r\n]+))([\'"])#i';
f5d2ee 784
AM 785     if (preg_match_all($regexp, $body, $matches, PREG_OFFSET_CAPTURE)) {
14bd92 786         // get domain for the Content-ID, must be the same as in Mail_Mime::get()
AM 787         if (preg_match('#@([0-9a-zA-Z\-\.]+)#', $from, $m)) {
788             $domain = $m[1];
789         }
790
f5d2ee 791         foreach ($matches[1] as $idx => $m) {
AM 792             $data = preg_replace('/\r\n/', '', $matches[3][$idx][0]);
793             $data = base64_decode($data);
794
795             if (empty($data)) {
796                 continue;
797             }
798
799             $hash      = md5($data) . '@' . $domain;
800             $mime_type = $matches[2][$idx][0];
801             $name      = $list[$hash];
802
14bd92 803             if (empty($mime_type)) {
AM 804                 $mime_type = rcube_mime::image_content_type($data);
805             }
806
f5d2ee 807             // add the image to the MIME message
AM 808             if (!$name) {
809                 $ext         = preg_replace('#^[^/]+/#', '', $mime_type);
810                 $name        = substr($hash, 0, 8) . '.' . $ext;
811                 $list[$hash] = $name;
812
813                 $mime_message->addHTMLImage($data, $mime_type, $name, false, $hash);
814             }
815
816             $body = substr_replace($body, $name, $m[1] + $offset, strlen($m[0]));
817             $offset += strlen($name) - strlen($m[0]);
818         }
819     }
820
821     $mime_message->setHTMLBody($body);
822 }
823
824 /**
825  * Parse and cleanup email address input (and count addresses)
826  *
827  * @param string  Address input
828  * @param boolean Do count recipients (saved in global $RECIPIENT_COUNT)
829  * @param boolean Validate addresses (errors saved in global $EMAIL_FORMAT_ERROR)
830  * @return string Canonical recipients string separated by comma
831  */
832 function rcmail_email_input_format($mailto, $count=false, $check=true)
833 {
834     global $RCMAIL, $EMAIL_FORMAT_ERROR, $RECIPIENT_COUNT;
835
836     // simplified email regexp, supporting quoted local part
837     $email_regexp = '(\S+|("[^"]+"))@\S+';
838
839     $delim   = trim($RCMAIL->config->get('recipients_separator', ','));
840     $regexp  = array("/[,;$delim]\s*[\r\n]+/", '/[\r\n]+/', "/[,;$delim]\s*\$/m", '/;/', '/(\S{1})(<'.$email_regexp.'>)/U');
841     $replace = array($delim.' ', ', ', '', $delim, '\\1 \\2');
842
843     // replace new lines and strip ending ', ', make address input more valid
844     $mailto = trim(preg_replace($regexp, $replace, $mailto));
845     $items  = rcube_utils::explode_quoted_string($delim, $mailto);
846     $result = array();
847
848     foreach ($items as $item) {
849         $item = trim($item);
850         // address in brackets without name (do nothing)
851         if (preg_match('/^<'.$email_regexp.'>$/', $item)) {
852             $item     = rcube_utils::idn_to_ascii(trim($item, '<>'));
853             $result[] = $item;
854         }
855         // address without brackets and without name (add brackets)
856         else if (preg_match('/^'.$email_regexp.'$/', $item)) {
857             $item     = rcube_utils::idn_to_ascii($item);
858             $result[] = $item;
859         }
860         // address with name (handle name)
861         else if (preg_match('/<*'.$email_regexp.'>*$/', $item, $matches)) {
862             $address = $matches[0];
863             $name    = trim(str_replace($address, '', $item));
864             if ($name[0] == '"' && $name[count($name)-1] == '"') {
865                 $name = substr($name, 1, -1);
866             }
867             $name     = stripcslashes($name);
868             $address  = rcube_utils::idn_to_ascii(trim($address, '<>'));
869             $result[] = format_email_recipient($address, $name);
870             $item     = $address;
871         }
872         else if (trim($item)) {
873             continue;
874         }
875
876         // check address format
877         $item = trim($item, '<>');
878         if ($item && $check && !rcube_utils::check_email($item)) {
879             $EMAIL_FORMAT_ERROR = $item;
880             return;
881         }
882     }
883
884     if ($count) {
885         $RECIPIENT_COUNT += count($result);
886     }
887
888     return implode(', ', $result);
889 }
890
891
892 function rcmail_generic_message_footer($isHtml)
893 {
894     global $RCMAIL;
895
896     if ($isHtml && ($file = $RCMAIL->config->get('generic_message_footer_html'))) {
897         $html_footer = true;
898     }
899     else {
900         $file = $RCMAIL->config->get('generic_message_footer');
901         $html_footer = false;
902     }
903
904     if ($file && realpath($file)) {
905         // sanity check
906         if (!preg_match('/\.(php|ini|conf)$/', $file) && strpos($file, '/etc/') === false) {
907             $footer = file_get_contents($file);
908             if ($isHtml && !$html_footer) {
909                 $footer = '<pre>' . $footer . '</pre>';
910             }
911             return $footer;
912         }
913     }
914
915     return false;
916 }